I'm using forms authentication in an ASP.NET application. I configure the FormsAuthenticationTicket
to expire in 1 year but it actually expires after 1 hour or so. I can't figure out why.
Here is all the code involved in the login process:
public static bool Login(int id)
{
try
{
string securityToken = UserHelper.AuthenticateUser(id);
DateTime expiryDate = DateTime.Now.AddYears(1);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, id.ToString(), DateTime.Now, expiryDate, true,
securityToken, FormsAuthentication.FormsCookiePath);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
cookie.Expires = expiryDate;
HttpContext.Current.Response.Cookies.Add(cookie);
return true;
}
catch
{
return false;
}
}
Web.config:
<system.web>
<machineKey validationKey="AutoGenerate"
decryptionKey="AutoGenerate" validation="SHA1" />
<compilation debug="true">
<authentication mode="Forms">
<forms loginUrl="~/Login.aspx" timeout="2880"/>
</authentication>
...
Is something wrong with my approach? Why is it expiring so fast?
EDIT
Global.asax code:
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (Request.PhysicalPath.EndsWith(".aspx") || Request.PhysicalPath.EndsWith(".axd") || Request.PhysicalPath.EndsWith(".ashx"))
SecurityManager.SetPrincipal();
}
SetPrincipal Code:
public static void SetPrincipal()
{
ILivrePrincipal principal = null;
FormsIdentity identity;
UrlParameters urlParameters = UrlParametersHelper.GetUrlParameters(HttpContext.Current.Request);
if (HttpContext.Current.Request.IsAuthenticated)
{
identity = (FormsIdentity)HttpContext.Current.User.Identity;
User userProfile;
urlParameters.SecurityToken = (((FormsIdentity)identity).Ticket).UserData;
try
{
userProfile = UserHelper.GetUser(urlParameters.SecurityToken);
UserHelper.UpdateLastActiveOn(userProfile);
principal = new AuthenticatedPrincipal(identity, userProfile);
}
catch
{
//TODO: Log an exception
FormsAuthentication.SignOut();
principal = new AnonymousPrincipal(new GuestIdentity(), UserHelper.GetUser(null));
}
}
else
{
principal = new AnonymousPrincipal(new GuestIdentity(), UserHelper.GetUser(null));
}
HttpContext.Current.User = principal;
}