1

I am creating a HttpCookie in my AccountController during the login process like so

FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);

When model.RememberMe is false I notice that I am never logged out, even if I restart the browser. Shouldn't the session expire after 20 minutes or on closing the browser?

I also, during the authentication process, set a cookie to store Role information using this method. This also sets a non persistent cookie. Is this affecting the login cookie?

What I notice is that, when I deserialize my cookie in Global.asax.cs the HttpCookie has an expiration of DateTime.MinValue and the authTicket has an expiration of up to 20minutes in the future. If I let this time elapse I do not notice the user logs out, in fact something has renewed the cookie as the expiration date jumps 20minutes or so in the future - but I can't see this happening within my code!

Can anyone help explain what is happening?

    protected void Application_PostAuthenticateRequest(object sender, EventArgs e)
    {
        HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];

        if (authCookie != null)
        {
            var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
            var serializer = new JavaScriptSerializer();
            var serializeModel = serializer.Deserialize<EMPrincipalSerializeModel>(authTicket.UserData);

            if (!authTicket.Expired && serializeModel != null && HttpContext.Current.User.Identity.IsAuthenticated)
            {
                var newUser = new EMPrincipal(authTicket.Name);
                newUser.Id = serializeModel.Id;
                newUser.RealName = serializeModel.RealName;
                newUser.Username = serializeModel.UserName;

                HttpContext.Current.User = newUser;
            }
        }
    }
Community
  • 1
  • 1
Chris
  • 26,744
  • 48
  • 193
  • 345

1 Answers1

1

Your authentication expiration is changing because of sliding expiration, meaning that on each request the expiration is reset to to x minutes in the future. This is the default behavior for FormsAuthentication. Authentication will only expire after x minutes of inactivity, each time you are invoking a request to check the session, you are renewing it.

You can disable this if you wish: https://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.slidingexpiration%28v=vs.110%29.aspx

If disabled, authentication will expire x minutes after creation, and not x minutes after inactivity.

Laurence Adams
  • 366
  • 1
  • 6