2014-01-16 26 views
0

我想通過使用下面的代碼創建窗體身份驗證Cookie。雖然這對於持久登錄非常有效,但當我關閉瀏覽器會話時,非持久性Cookie不會過期並從瀏覽器中刪除。它仍然保留在瀏覽器中。FormsAuthentication非持久性Cookie不會在MVC 4中過期應用程序

public static void SetAuthenticationCookie(string userName, Role role, 
bool isPersistent) 
{ 
string data = role.RoleName; 
HttpCookie authCookie = FormsAuthentication.GetAuthCookie(userName,isPersistent); 
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value); 
FormsAuthenticationTicket newticket = new FormsAuthenticationTicket(
ticket.Version, ticket.Name, ticket.IssueDate,ticket.Expiration, 
ticket.IsPersistent,data); 
    authCookie.Value = FormsAuthentication.Encrypt(newticket); 
    HttpContext.Current.Response.Cookies.Add(authCookie);    
} 

這裏是窗體身份驗證

<authentication mode="Forms"> 
    <forms loginUrl="~/Account/Login" cookieless="UseCookies" name=".OneClick" 
    protection="All" slidingExpiration="true" timeout="43200" /> 
</authentication> 

這裏的web.config條目的cookie信息從瀏覽器

Cookie Information

截圖有什麼我失蹤這裏?請讓我知道

回答

0

我不確定這是否正確的解決方案。但我發現即使cookie過期設置爲之前的日期時間,表單身份驗證票證過期從web.config中設置,使其行爲像持久性cookie。所以我嘗試設置1分鐘作爲cookie和票據過期,這使得cookie和票證在1分鐘的超時期限後過期。

即使非持久性cookie在瀏覽器會話結束後應該過期。出於某種原因,此cookie將保留,直至表單身份驗證cookie過期。

以下是解決方案。

public static void SetAuthenticationCookie(string userName, Role role, 
        bool isPersistent) 
{ 
    string data = role.RoleName; 
    HttpCookie authCookie = FormsAuthentication.GetAuthCookie(userName, 
    isPersistent);    

    if (!isPersistent) 
    { 
    authCookie.Expires = DateTime.Now.AddMinutes(30); 
    } 

FormsAuthenticationTicket ticket=FormsAuthentication.Decrypt(authCookie.Value);   
FormsAuthenticationTicket newticket= 
new FormsAuthenticationTicket(ticket.Version,ticket.Name, ticket.IssueDate, 
authCookie.Expires, ticket.IsPersistent, data);    
authCookie.Value = FormsAuthentication.Encrypt(newticket); 
HttpContext.Current.Response.Cookies.Add(authCookie);    
} 

建議或改進,歡迎。

謝謝

相關問題