Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create non-persistent cookie with FormsAuthenticationTicket

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?

like image 313
Marcus Avatar asked Nov 30 '09 11:11

Marcus


People also ask

What does Formsauthentication SetAuthCookie do?

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.

What is Aspxauth cookie?

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.

What is Formsauthentication FormsCookieName?

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.


1 Answers

Try deleting:

if (isPersistent) { cookie.Expires = expiration; }

... and replacing it with:

if (!isPersistent) { cookie.Expires = DateTime.Now.AddYears(-1); }

like image 131
Richard Avatar answered Sep 24 '22 03:09

Richard