14

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?

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
Don
  • 426
  • 1
  • 4
  • 9

1 Answers1

27

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);
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • THanks, I will set them both to 30 minutes, Are there values stored anywhere else that might cause the user to be able to login once, but then not again after they timeout? – Don Mar 03 '11 at 01:49
  • 1
    Small correction - that should be `Secure = FormsAuthentication.RequireSSL`, the `HttpOnly` setting just makes the cookie hidden from Javascript (in proper browsers, IE6 doesn't support it). – Keith Jul 11 '12 at 08:29
  • 1
    HTH :-) Mind you, you should probably have `HttpOnly = true` too as it protects from XSS attacks stealing cookies. – Keith Jul 11 '12 at 10:27