asp.net mvc身份验证cookie问题

Dea*_*ean 2 asp.net-mvc

我正在尝试使用ASP.NET MVC实现"记住我"功能.它使用如下定义的自定义身份验证过程.

Web.config文件:

    <authentication mode="Forms">
        <forms loginUrl="/Account/Login" defaultUrl="/Home/MyAccount" timeout="43200"/>
    </authentication>
Run Code Online (Sandbox Code Playgroud)

用于持久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);
}
Run Code Online (Sandbox Code Playgroud)

检索cookie的代码:

        if (System.Web.HttpContext.Current.Request.Cookies.AllKeys.Contains(FormsAuthentication.FormsCookieName)) {
            cookie = System.Web.HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
        }
Run Code Online (Sandbox Code Playgroud)

当前代码检查Session以进行身份​​验证.我想添加从cookie获取userName的功能.我有两个问题:

  1. 为了检索cookie,我需要做什么?
  2. 如何解密cookie以获取userName?

干杯,

院长

Pat*_*ele 6

获取cookie:

HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(FormsAuthentication.FormsCookieName);
Run Code Online (Sandbox Code Playgroud)

解密它:

FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
var userName = ticket.UserData
Run Code Online (Sandbox Code Playgroud)