ASP.NET Forms Authentication "Remember Me"
by Alex Yumashev ·
Jul 27 2009
Another post for ASP.NET developers. By the way if you think these posts do not belong to this blog, please leave a comment, and I'll consider moving my development articles to a separate blog.
Today I needed to set up a "remember me" functionality for our web-based HelpDesk app
and small-business CRM app
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)
DateTime expires = DateTime.Now.AddDays(20);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
expires, // value of time out property
true, // Value of IsPersistent property
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie authCookie = new HttpCookie(
authCookie.Expires = expires;
string returnUrl = FormsAuthentication.GetRedirectUrl(userName, true);
if (string.IsNullOrEmpty(returnUrl)) returnUrl = "Default.aspx";