开发者

asp.net mvc authentication cookie issue

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);

    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)) {
            开发者_StackOverflowcookie = 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?


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜