Create non-persistent cookie with FormsAuthenticationTicket
Asked Answered
R

1

7

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?

Rotogravure answered 30/11, 2009 at 11:53 Comment(0)
I
3

Try deleting:

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

... and replacing it with:

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

Ipomoea answered 23/2, 2011 at 16:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.