持久性AuthCookie已设置,但被重定向到登录

我在使用持久性AuthCookie时遇到问题。 validation和登录工作完美,如果我关闭浏览器并重新打开它,身份validation仍然有效,不会重定向到登录页面。 我不知道确切的时间是什么,但是让我们说如果关闭浏览器而不注销并且仅在20分钟后重新打开它我将被重定向到登录页面,即使我在使用web开发人员工具检查时设置了cookie它的到期日期是从现在开始的一个月。

validation用户凭据后我正在做的所有事情都是

FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe); 

在我的Web.Config中我设置了它

   ...    ... 

还尝试按照此处和其他一些地方对机器密钥进行硬编码,但无效

  

我正在努力解决这个问题

 //this line is NOT ENOUGH for "remember me" to work!!! FormsAuthentication.SetAuthCookie(userName, true); //DOESN'T WORK! //########### //you have to save the "remember me" info inside the auth-ticket as well //like this: DateTime expires = DateTime.Now.AddDays(20); //remember for 20 days //create the auth ticket FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now, expires, // value of time out property true, // Value of IsPersistent property!!! String.Empty, FormsAuthentication.FormsCookiePath); //now encrypt the auth-ticket string encryptedTicket = FormsAuthentication.Encrypt(ticket); //now save the ticket to a cookie HttpCookie authCookie = new HttpCookie( FormsAuthentication.FormsCookieName, encryptedTicket); authCookie.Expires = expires; //feed the cookie to the browser HttpContext.Current.Response.Cookies.Add(authCookie); 

检查您的IIS设置。

1)默认情况下,IIS 7(以及IIS 8以及内存服务器)在运行时为每个应用程序池生成唯一的加密密钥 。 在运行时生成意味着只要应用程序池重新启动,就会重新生成密钥。 这意味着在应用程序池重新启动后,应用程序池重新启动之前生成的持久性cookie不会被解密,用户将无法使用旧cookie进行身份validation,并将进入登录页面。

2)IIS具有默认空闲超时 – 20分钟。 这意味着如果应用程序在20分钟内未收到单个请求,则应用程序池将关闭。 然后当请求进入时它将重新开始。

上述两种设置的组合可能会导致您描述的行为。

PS。 您可能还想检查应用程序事件日志 – 如果确实解密失败,那么您将遇到例外 – “无法validation数据”行