Sunday, 5 May 2013

ASP.NET Forms Authentication "Remember Me"

Today I needed to set up a "remember me" functionality for website's login pages. If you ever tried to achieve this using .NET's FormsAuthentication, you might have noticed that... it's just not working. Even if you pass the "createPersistentCookie" parameter value as "true" when initializing FormsAuthentication - the cookie still lives for a limited time only - the time specified as the Forms-Authentication timeout in "web.config". Then the cookie dies.

The only solution was to increase that timeout value in web.config. And it's not a very good idea because of the security reasons.

The solution is to set the authentication cookie timeout explicitly. See the code, which is pretty self-explaining:

private void FormsAuthLogin(string userName, bool rememberMe)
{
  if (!rememberMe)
  {
    FormsAuthentication.RedirectFromLoginPage(userName, false);
  }
  else
  {
    FormsAuthentication.Initialize();
    DateTime expires = DateTime.Now.AddDays(20);
    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
      userName,
      DateTime.Now,
      expires, // value of time out property
      true, // Value of IsPersistent property
      String.Empty,
      FormsAuthentication.FormsCookiePath);

    string encryptedTicket = FormsAuthentication.Encrypt(ticket);

    HttpCookie authCookie = new HttpCookie(
          FormsAuthentication.FormsCookieName,
          encryptedTicket);
    authCookie.Expires = expires;

    Response.Cookies.Add(authCookie);

    string returnUrl = FormsAuthentication.GetRedirectUrl(userName, true);
    if (string.IsNullOrEmpty(returnUrl)) returnUrl = "Default.aspx";
    Response.Redirect(returnUrl);
  }
}

No comments:

Post a Comment