0

I am having an issue with a cookie expiring too soon for an ASP.Net web application.

I have set the cookie to expire after 3 hours and have not set a timeout in the webconfig, yet the user is directed to the login screen after 1 hour.

If I set the cookie expiry time to 1 minute, it logs the user out after 1 minute, so I am guessing something else is overriding it after an hour, but I am not sure where to look.

My forms authentication and session state web config entries, as well as the code for creating the cookie and looking up the cookie can be seen below.

<sessionState mode="InProc" timeout="525600" />
<authentication mode="Forms">
  <forms loginUrl="~/Login.aspx" name=".VRBAdmin" enableCrossAppRedirects="false" cookieless="UseCookies" />
</authentication>
<authorization>

protected void OnLogin(object sender, EventArgs e)
    {
        if (Membership.ValidateUser(this.uxUser.Text, this.uxPassword.Text))
        {
            string userData = string.Join("|", Roles.GetRolesForUser(this.uxUser.Text));

            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
            1,                                     // ticket version
            this.uxUser.Text,                              // authenticated username
            DateTime.Now,                          // issueDate
            DateTime.Now.AddHours(3),               // expiryDate
            true,                                  // true to persist across browser sessions
            userData,                                  // can be used to store additional user data
            FormsAuthentication.FormsCookiePath);  // the path for the cookie

            // Encrypt the ticket using the machine key
            string encryptedTicket = FormsAuthentication.Encrypt(ticket);

            // Add the cookie to the request to save it
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
            cookie.HttpOnly = true;
            Response.Cookies.Add(cookie);

            // Your redirect logic
            Response.Redirect(FormsAuthentication.GetRedirectUrl(this.uxUser.Text, true));
        }
    }

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
    {
        HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
        if (authCookie != null)
        {
            //Extract the forms authentication cookie
            FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);

            // If caching roles in userData field then extract
            string[] roles = authTicket.UserData.Split(new char[] { '|' });

            // Create the IIdentity instance
            IIdentity id = new FormsIdentity(authTicket);

            // Create the IPrinciple instance
            IPrincipal principal = new GenericPrincipal(id, roles);

            // Set the context user 
            Context.User = principal;
        }
    }
user1948635
  • 1,357
  • 4
  • 15
  • 22

1 Answers1

0

If you use ASP.NET Member Provider, you should not create FormsAuthenticationTicket by yourself. You don't even need to manually create principal object inside Application_AuthenticateRequest event.

Instead, you want to let Membership Provider do all the heavy lifting.

Normally, session timeout should be twice smaller than authentication cookie timeout, because we need to free up resources.

<sessionState timeout="180" />
<authentication mode="Forms">
   <forms ...  timeout="360" />
</authentication>


protected void OnLogin(object sender, EventArgs e)
{
   if (Membership.ValidateUser(this.uxUser.Text, this.uxPassword.Text))
   {
       FormsAuthentication.SetAuthCookie(this.uxUser.Text, RememberMeSet);
       ...
   }
}

Also increase application pool timeout if your application doesn't have enough traffic.

Win
  • 61,100
  • 13
  • 102
  • 181
  • Im actually trying to increase the timeout to a week or more, which I dont think is possible using the membership provider as is. Thats why I put in the manual cookie creation, the creation/lookup code was found online. Is there a way to do this with membership doing the work? – user1948635 Oct 11 '18 at 09:01
  • Yes, you can do it with Membership Provider only. Settings in my answer should work. Please ensure cookie time out is at least twice larger than session time out. – Win Oct 11 '18 at 15:22