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;
}
}