ASP.NET 4.5 持久性 cookie 无法正常工作

ASP.NET 4.5 persistent cookies not working correctly

我们有一个客户的 Web 表单项目,该项目保持 "timing out" 并且会在管理区域填写信息时定期注销用户。我们 运行 在之前的项目中遇到了类似的事情,但我们能够通过这个轻松解决这个问题:

if (RememberMe.Checked)
{
    FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket((string)r["Login"], true, (90*24*60));
    string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
    cookie.Expires = authTicket.Expiration;
    HttpContext.Current.Response.Cookies.Set(cookie);
    Response.Redirect(FormsAuthentication.GetRedirectUrl((string)r["Login"], false), true);
}
else
{
    FormsAuthentication.SetAuthCookie((string)r["Login"], false);
    FormsAuthentication.RedirectFromLoginPage((string)r["Login"], false);
}

当我在新项目上尝试同样的方法时,它没有效果。我能弄清楚的唯一区别(在多次重写和调整之后)是新项目使用的是 .NET 4.5,而它工作的项目是 .NET 4.0。这是 4.5 中的错误吗?还有其他人遇到过吗?

我们将新项目降级到 4.0 只是为了看看,到目前为止它似乎工作完美,没有任何额外的代码更改。我的大部分搜索结果都给出了一个代码示例,看起来几乎和我已经在做的一模一样。

如果其他人遇到同样的问题,我们在这里找到了解决方案:http://blog.falafel.com/asp-net-forms-authentication-times-out-on-a-shared-host/

Because that application didn’t have it’s own machineKey, it was inheriting the one from the server’s machine.config. This one was configured to auto-generate since it was for a server shared by multiple customers, and it would be a major security flaw if they all shared the same key. Because the key was auto-generating, though, it was also getting regenerated every time the application reset, and failing to decrypt previously handed-out Forms Authentication cookies.

I needed to set a machineKey for my application, so I created a key and put it in a machineKey tag in my application’s web.config, and voila, it worked!

它在旧站点上运行的原因可能是它具有相当稳定的流量并且可能没有足够长的空闲时间来重新生成机器密钥。但是,一旦我们在新站点上设置了机器密钥,它就可以完美运行:https://blogs.msdn.microsoft.com/amb/2012/07/31/easiest-way-to-generate-machinekey/