FormsAuthenticationTicket.expiration v web.config value timeout

10.6k views Asked by At

This is an MVC2 website, I am having a problem with a FormsAuthentication ticket. A user timeouts after 30 minutes cannot re-login. During testing, the DateTime.Now.AddMinutes(30) value was set to 5000 and everything was ok, but it has now changed to 30 and that is when then the problem started

From cookie creation

 FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
            1,
            user.UserID,
            DateTime.Now,
            DateTime.Now.AddMinutes(30),
            false,
            "user,user1",
            FormsAuthentication.FormsCookiePath);

Web.config file

<authentication mode="Forms">
  <forms loginUrl="~/Account.mvc/LogOn" timeout="2880" name=".ASPXFORMSAUTH" />
</authentication>

Does the expiration value in ticket creation need to be >= web.config value?

1

There are 1 answers

3
Darin Dimitrov On BEST ANSWER

Because you are manually creating the authentication cookie, the timeout value in your web.config is completely ignored. So I would recommend you having the same value:

var ticket = new FormsAuthenticationTicket(
    1,
    user.UserID,
    DateTime.Now,
    DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes),
    false,
    "user,user1",
    FormsAuthentication.FormsCookiePath
);
var encryptedTicket = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
{
    HttpOnly = true,
    Secure = FormsAuthentication.RequireSSL,
    Path = FormsAuthentication.FormsCookiePath,
    Domain = FormsAuthentication.CookieDomain
};
Response.AppendCookie(cookie);