Search code examples
c#cookiesforms-authentication.aspxauth

Expire ASPXAUTH Cookie when browser closes


I'm creating an ASPXAUTH cookie by using the following code

var authTicket = new FormsAuthenticationTicket(2, model.Name, DateTime.Now, DateTime.Now.AddMinutes(ConfigSettings.SessionTimeout),
                    false, result.UniqueId.ToString());

                var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName,
                    FormsAuthentication.Encrypt(authTicket))
                {
                    HttpOnly = true,
                    Expires = authTicket.Expiration                    
                };

                Response.AppendCookie(authCookie);

When the user closes the browser (both IE and Chrome) and logs in again the session is still active, the APSXAUTH cookie is not expired. I've set it to be non persistent. I'm also certain all browser instances have been closed.

What am I missing?


Solution

  • Since you manually set the Expires property, the browser creates a persistent cookie at the client side.

    Just do not set any value there, comment out that line. This will create a cookie that lasts as long as the browser is open.

    Note that usually it means that even if a user closes the tab, the cookie is still there. It disappears when the browser process is closed and restarted.