Create non-persistent cookie with FormsAuthenticationTicket

Posted by Marcus on Stack Overflow See other posts from Stack Overflow or by Marcus
Published on 2009-11-30T11:53:15Z Indexed on 2010/05/15 23:10 UTC
Read the original article Hit count: 950

Hello!

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?

Thanks in advance!

/Marcus

© Stack Overflow or respective owner

Related posts about forms-authentication

Related posts about ticket