I'm having trouble creating a non-persistent cookie using the FormsAuthenticationTicket. I want to store userdata in the ticket, so i can't use FormsAuthentication.SetAuthCookie() or FormsAuthentication.GetAuthCookie() methods. Because of this I need to create the FormsAuthenticationTicket and store it in a HttpCookie.
My code looks like this:
DateTime expiration = DateTime.Now.AddDays(7);
// Create ticket
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2,
user.Email,
DateTime.Now,
expiration,
isPersistent,
userData,
FormsAuthentication.FormsCookiePath);
// Create cookie
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
cookie.Path = FormsAuthentication.FormsCookiePath;
if (isPersistent)
cookie.Expires = expiration;
// Add cookie to response
HttpContext.Current.Response.Cookies.Add(cookie);
When the variable isPersistent is true everything works fine and the cookie is persisted. But when isPersistent is false the cookie seems to be persisted anyway. I sign on in a browser window, closes it and opens the browser again and I am still logged in. How do i set the cookie to be non-persistent?
Is a non-persistent cookie the same as a session cookie? Is the cookie information stored in the sessiondata on the server or are the cookie transferred in every request/response to the server?
The SetAuthCookie method adds a forms-authentication ticket to either the cookies collection, or to the URL if CookiesSupported is false . The forms-authentication ticket supplies forms-authentication information to the next request made by the browser.
The ASPXAUTH cookie is used to determine if a user is authenticated. As far as the location of the cookie, that depends on your browser. If you are using Firefox you can view the cookie by clicking on Tools -> Options -> Privacy.
The FormsCookieName property value is set in the configuration file for an ASP.NET application by using the name attribute of the forms configuration element. The FormsCookieName is used to reference the cookie that stores the FormsAuthenticationTicket information.
Try deleting:
if (isPersistent)
{ cookie.Expires = expiration; }
... and replacing it with:
if (!isPersistent) {
cookie.Expires = DateTime.Now.AddYears(-1); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With