2010-11-05 52 views
13

OK,這裏是我的代碼來創建一個身份驗證Cookie:問題創造持久的身份驗證Cookie:ASP.NET MVC

 // get user's role 
     List<UserType> roles = rc.rolesRepository.GetUserRoles(rc.userLoginRepository.GetUserID(userName)); 
     List<string> rolesList = (from r in roles 
           select r.ToString()).ToList(); 
     string[] rolesArr = rolesList.ToArray(); 

     // create encryption cookie 
     FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
       1, 
       userName, 
       DateTime.Now, 
       DateTime.Now.AddDays(90), 
       createPersistentCookie, 
       String.Join(";",rolesArr) //user's roles 
       ); 

     // add cookie to response stream 
     string encryptedTicket = FormsAuthentication.Encrypt(authTicket); 

     System.Web.HttpCookie authCookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); 
     System.Web.HttpContext.Current.Response.Cookies.Add(authCookie); 
     //FormsAuthentication.SetAuthCookie(userName, createPersistentCookie); 

,這裏是我在Global.asax中代碼的用戶角色設置到用戶的身份:

protected void Application_AuthenticateRequest(Object sender, EventArgs e) 
    { 
     HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName]; 
     if (authCookie == null || authCookie.Value == "") 
     { 
      return; 
     } 
     FormsAuthenticationTicket authTicket = null; 
     try 
     { 
      authTicket = FormsAuthentication.Decrypt(authCookie.Value); 
      string[] roles = authTicket.UserData.Split(new char[] { ';' }); 
      if (Context.User != null) 
      { 
       Context.User = new System.Security.Principal.GenericPrincipal(Context.User.Identity, roles); 
      } 
     } 
     catch 
     { 
      return; 
     } 
    } 

但是,如果在頂部示例中「createPersistentCookie」爲TRUE,則不會創建持久性cookie。如果我取消最後一行的註釋,如下所示:

 //System.Web.HttpContext.Current.Response.Cookies.Add(authCookie); 
     FormsAuthentication.SetAuthCookie(userName, createPersistentCookie); 

然後在我的硬盤上創建持久性cookie。但是,在Global.asax代碼中,「authTicket」中的UserData字段爲空,因此我無法正確設置角色!

所以我必須使用SetAuthCookie創建一個持久性cookie,但是由於某種原因UserData字段從持久性cookie中消失。

這是什麼答案?

回答

17

來創建一個持久的cookie,你需要設置Expires屬性:

if (authTicket.IsPersistent) 
{ 
    authCookie.Expires = authTicket.Expiration; 
} 
+0

沒錯,就是做到了!非常感謝。我一直在撕掉我的頭髮。現在我可以使用Response.Cookies.Add而不是SetAuthCookie,並創建一個持久性cookie,並且UserData不會被刪除(奇怪!) – Cynthia 2010-11-09 00:40:50