When I log I create the following cookie:
HttpCookie cookie = new HttpCookie("Ortund");
// insert cookie values
cookie.Expires = DateTime.Now.AddMonths(1);
Response.Cookies.Add(cookie);
When I request data from this cookie, I use Request.Cookies:
string username = Convert.ToString(Request.Cookies["Ortund"]["Username"]);
When i log out, I do this:
HttpCookie cookie = new HttpCookie("Ortund");
cookie.Expires = DateTime.Now.AddMonths(-1);
Response.Cookies.Add(cookie);
For some reason, now I'm sitting with a cookie that has an expiry date of 0001-01-01 12:00:00 AM in Request.Cookies["Ortund"] and the expiry date of the cookie doesn't change no matter how many times I log in.
Have I done something wrong here? Is this even close to how it should be done?
In your logout you are creating a new instance of the cookie. Also you are using Response.Cookies.Add which may allow multiple cookies of the same name to be appended to the Response.
I would suggest you to check the Request for the cookie key and if it doesn't exist add the cookie.
For updating the cookie, first get the existing cookie object and use Response.SetCookie to update the value.
Code
set
if(!Request.Cookies.AllKeys.Contains("Ortund"))
{
HttpCookie cookie = new HttpCookie("Ortund");
// insert cookie values
cookie.Expires = DateTime.Now.AddMonths(1);
Response.Cookies.Add(cookie);
}
update
if (Request.Cookies.AllKeys.Contains("Ortund"))
{
HttpCookie cookie = Request.Cookies["Ortund"];
cookie.Expires = DateTime.Now.AddMonths(-1);
Response.SetCookie(cookie);
}
Related
I have getting issue with delete FormsAuthentication ticket cookie with remember me option.. it always showing expired date 01/01/0001, I am setting FormsAuthentication ticket with expired time at the time of login controller.
When the application URL open that time again check the expired time & Auth Cookie.
everytime it Authentication cookies expired time showing the same..
How to manage FormsAuth ticket with remember me option?
I have search a lots in different forums but not get the exact solutions..
Below screenshot when i have not selected Remember me.
When I selected remember me it showing time in Expire age. but not handling with C# code.
// Here u is view model object that set the username,password and remember me options.
// LOGIN FUNCTION CODE
if (u.RememberMe)
{
int timeout = u.RememberMe ? 525600 : (int)sessionSection.Timeout.TotalMinutes; // Timeout in minutes, 525600 = 365 days.
var ticket = new FormsAuthenticationTicket(1, u.Email, DateTime.UtcNow, DateTime.UtcNow.AddMinutes(timeout), u.RememberMe, logmodel.UserType);
string encrypted = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
cookie.Path = FormsAuthentication.FormsCookiePath;
//cookie.Expires = System.DateTime.UtcNow.AddMinutes(timeout);// Not my line
//if (ticket.IsPersistent)
// cookie.Expires = ticket.Expiration;
cookie.Expires = ticket.Expiration;
/// cookie.HttpOnly = true; // cookie not available in javascript.
Response.Cookies.Add(cookie);
}
else
{
FormsAuthentication.SetAuthCookie(u.Email, false);
}
Hi I am creating a cookie in the following way:
HttpCookie cookie = new HttpCookie("CookieNameHere");
cookie.Values["test1"] = "Value1";
cookie.Values["test2"] = "Value2";
cookie.Values["test3"] = "Value3";
//I have also tried cookie.Values.Add("test1", "Value1");
cookie.Expires = DateTime.Now.AddDays(365d);
HttpContext.Current.Response.AppendCookie(cookie); //here I have also tried HttpContext.Current.Response.Cookies.Add(cookie);
but when I read out the cookie using the following code:
HttpCookie cookie = new HttpCookie("CookieNameHere");
cookie = HttpContext.Current.Response.Cookies["CookieNameHere"];
I always get that the cookie.Values is empty
Is there something I am doing wrong here?
Normally you would write the cookie in a Response, and then read it from subsequent Requests.
I see you're trying to read it from the Response - is this within the context of the same HTTP request, or just a typo?
Try
HttpCookie cookie = HttpContext.Current.Request.Cookies["CookieNameHere"];
You have to ask for those Cookies in a Request.
HttpCookie cookie = Request.Cookies["CookieName"];
I am writing a "Remember My Username" Cookie that expires in a custom duration of time e.g. one month. I noticed that when I add HttpOnly = true, the expiration changes to session. Why is this? I can't seem to find any documentation on why this would happen.
Thanks.
Here is the documentation.
true if the cookie has the HttpOnly attribute and cannot be accessed
through a client-side script; otherwise, false. The default is false.
Basically, it becomes a session variable because it will only be stored on the server due to your setting
I'm adding the following code: Also, now I'm getting a different behaviors than the Title. I'm running this locally against the VS2010 built-in server. It seems to show inconsistent behaviors. I would move the HttpOnly = true before the Expires and after it and it seemed to change behavior until I refreshed the browser page. So, I am assuming everything was fine and never had an issue. In addition, I am moving HttpOnly and Secure flags to the web.config because not all my environments have SSL.
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket
(strUserID, //name
false, //IsPersistent
24 * 60); // 24 hours
// Encrypt the ticket.
string encryTicket = FormsAuthentication.Encrypt(ticket);
// Create the cookie.
HttpCookie userCookie = new HttpCookie("Authentication", encryTicket);
userCookie.HttpOnly = true;
Response.Cookies.Add(userCookie);
e.Authenticated = true;
if (LoginPannelMain.RememberMeSet)
{
HttpCookie aCookie = new HttpCookie("email", strUserLogin);
aCookie.HttpOnly = true;
aCookie.Expires = DateTime.Now.AddYears(1);
Response.AppendCookie(aCookie);
}
else
{
HttpCookie aCookie = new HttpCookie("email", "");
aCookie.HttpOnly = true;
Response.AppendCookie(aCookie);
}
I am creating the cookie using the code below, How to read the txtusername value in another page and how to delete the cookie when I click sign out(code for sign out). I am new to programming please help.
string cookiestr;
HttpCookie ck;
tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now,
DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, "your custom data");
cookiestr = FormsAuthentication.Encrypt(tkt);
ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
if (chkPersistCookie.Checked)
ck.Expires = tkt.Expiration;
ck.Path = FormsAuthentication.FormsCookiePath;
Response.Cookies.Add(ck);
You should never store password as a cookie. That's a very big security threat. To delete a cookie, you really just need to modify and expire it. You can't really delete it, i.e. remove it from the user's disk. Check out this documentation.
Here is a sample:
HttpCookie aCookie;
string cookieName;
int limit = Request.Cookies.Count;
for (int i=0; i<limit; i++)
{
cookieName = Request.Cookies[i].Name;
aCookie = new HttpCookie(cookieName);
aCookie.Expires = DateTime.Now.AddDays(-1); // make it expire yesterday
Response.Cookies.Add(aCookie); // overwrite it
}
You cannot directly delete a cookie, you have to set it to expire before the current date:
if (Request.Cookies["clienDetails"] != null)
{
HttpCookie myCookie = new HttpCookie("clienDetails");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
You can read more about it here.
Furthermore I really encourage you to not write your own security but to read up on asp.net membership. More secure and easier to use. As I can see many flaws in your security model. Storing the password in plain text in a cookie is really really bad.
EDIT:
As you now changed your code, you have to do this to remove the cookie:
if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
HttpCookie myCookie = new HttpCookie(FormsAuthentication.FormsCookieName);
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
FYI this did not work for me using Chrome 69 with the Continue where you left off feature enabled. Similar issue with Firefox. Disabling this feature worked for me.
See
Chrome doesn't delete session cookies
How to delete or expire a cookie in Chrome using Asp.Net
In my case this code worked:
Response.Cookies.Delete("access_token");
return Ok();
When a user logs in to my site, I create a cookie with some info in it. However, whenever they change page from logging in, the cookie loses it's value. Cookie is still there but it's empty.
I've checked my code and the cookie doesn't get rewritten by anything I've done.
Does anyone have any idea to why the cookie becomes empty when the page is changed?
Here's the method for creating the cookie.
public static void CreateUserCookie(long userId, string username, bool rememberMe) {
HttpCookie cookie = new HttpCookie("CookieName");
cookie.Value = string.Format("{0}+{1}+{2}", userId, username, SecurityUtils.CreateHashedCookieValue(userId, username));
if (rememberMe) {
cookie.Expires = DateTime.Now.AddMonths(1);
} else {
cookie.Expires = DateTime.MinValue;
}
HttpContext.Current.Response.Cookies.Add(cookie);
}
When you call this method, do you pass in true for the "rememberMe" parameter? If not, the cookie will instantly expire.
You haven't shown your calling code, so this is potentially what you've done.