środa, 23 września 2009

ASP.NET MVC "Remember me" and FormsAuthentication timeout

Recently I came across a strange behavior of ASP FormsAuthentication class. As it is said in "Pro ASP.NET 3.5 in C# 2008" book forms authentication should create persistent cookie when user marks "Remember me" checkbox in login control. Persistent cookie should avoid logging off user when he closes browser or when default timeout passes (it is configured in forms authentication section in Web.Config file).
Listing 1: Web.Config - Forms authentication configuration
  
         
  

To avoid logging off user even if default timeout goes by I needed to edit SignIn method from FormsAuthenticationService class which is placed in AccountController.cs file.
Listing 2: Updated SignIn method
public void SignIn(string userName, bool createPersistentCookie)
{
    // Remember me was checked - set cookie to remember user for 10 days (or until he logs off)
    if (createPersistentCookie)
    {
        var tenDaysFromNow = DateTime.Now.AddDays(10);
        FormsAuthentication.Initialize();
        HttpCookie cookie = FormsAuthentication.GetAuthCookie(userName, createPersistentCookie);
        cookie.Expires = tenDaysFromNow;
        var cookieVal = FormsAuthentication.Decrypt(cookie.Value);
        FormsAuthenticationTicket at = new FormsAuthenticationTicket(cookieVal.Version, cookieVal.Name, cookieVal.IssueDate, tenDaysFromNow, true, cookieVal.UserData);
        cookie.Value = FormsAuthentication.Encrypt(at);
        HttpContext.Current.Response.Cookies.Add(cookie);                                              
    }            
    else
    {
        FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);                 
    }            
}

The code grabs default authentication cookie (line 8), decrypts its value in line 10 and based on existing value creates new Authentication Ticket with updated ExpirationDate. In the end cookie has been added to response cookies collection.

Brak komentarzy: