Asp.net
為什麼我的 ASP.NET MVC 持久身份驗證 cookie 不起作用?
我正在使用帶有表單身份驗證的 ASP.NET MVC 3(基於通過 file->new 獲得的修改後的 vanilla 帳戶程式碼)。
當您登錄時,我正在設置一個身份驗證 cookie
FormsAuthentication.SetAuthCookie(userName, true);所以這應該設置一個持久的cookie。但是如果我關閉瀏覽器並重新打開,當我瀏覽到該站點時,我將被迫再次登錄!我可以看到使用 chrome 開發工具,當我關閉瀏覽器時,cookie (.ASPXAUTH) 正在創建並且沒有被刪除,那麼發生了什麼?
我的 web.config:
<authentication mode="Forms"> <forms loginUrl="~/Account/LogIn" timeout="10000"/> </authentication>如果這有什麼不同,我正在本地測試這個,在 IIS 下。
從@alexl 的評論中解決:
你可以檢查這個答案:使用 ASP .Net Membership 使使用者登錄持久化
好的,這個連結似乎為我排序 - 堅持使用 SetAuthCookie 並調整我的配置以明確設置 cookie 名稱(在 web.confg 中),現在一切正常。詭異的!–
我最好使用身份驗證票為自己創建一個 cookie。
SetAuthCookie在後台創建身份驗證票。您是否嘗試過製作自己的身份驗證票?它會讓你在上面儲存額外的數據。這是一個例子:
// create encryption cookie FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddDays(90), createPersistentCookie, string.Empty); // add cookie to response stream string encryptedTicket = FormsAuthentication.Encrypt(authTicket); System.Web.HttpCookie authCookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); if (authTicket.IsPersistent) { authCookie.Expires = authTicket.Expiration; } System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);希望這可以幫助。