tags:

views:

25

answers:

1

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:

  1. What do I need to do in order to retrieve the cookie?
  2. How do I decrypt the cookie to obtain the userName?

Cheers,

Dean

A: 

To get the cookie:

HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(FormsAuthentication.FormsCookieName);

Decrypt it with:

FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
var userName = ticket.UserData
Patrick Steele
Thanks, that works great. I also realized that I needed to remove the code FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
Dean