2010-10-27 248 views
2

我正在尝试使用ASP.NET MVC实现“记住我”功能。它使用定义如下的定制认证过程。asp.net mvc身份验证cookie问题

Web.config文件:

<authentication mode="Forms"> 
     <forms loginUrl="/Account/Login" defaultUrl="/Home/MyAccount" timeout="43200"/> 
    </authentication> 

代码坚持饼干:

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

代码检索的cookie:

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

当前的代码检查会话进行身份验证。我想添加从cookie中获取userName的功能。我有两个问题:

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

干杯,

院长

回答

6

要获取的cookie:

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

与解密:

FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value); 
var userName = ticket.UserData 
+0

谢谢,这伟大工程。我也意识到我需要删除代码FormsAuthentication.SetAuthCookie(userName,createPersistentCookie); – Dean 2010-10-28 15:46:59