I'm trying to implement a "remember me" feature using ASP.NET MVC. It uses a customized authentication process as defined below.
Web.config:
<authentication mode="Forms">
<forms loginUrl="/Account/Login" defaultUrl="/Home/MyAccount" timeout="43200"/>
</authentication>
Code to persist cookie:
public void SignIn(string userName, bool createPersistentCookie) {
int timeout = createPersistentCookie ? 525600 : 120; // Timeout in minutes, 525600 = 365 days.
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(userName, createPersistentCookie, timeout);
string encrypted = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
cookie.Expires = System.DateTime.Now.AddMinutes(timeout);
Blockquote
HttpContext.Current.Response.Cookies.Add(cookie);
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
}
Code to retrieve cookie:
if (System.Web.HttpContext.Current.Request.Cookies.AllKeys.Contains(FormsAuthentication.FormsCookieName)) {
cookie = System.Web.HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
}
The current code checks for Session for authentication. I'd like to add the ability to get the userName from cookie as well. I have 2 questions:
- What do I need to do in order to retrieve the cookie?
- How do I decrypt the cookie to obtain the userName?
Cheers,
Dean