我想在我的应用程序上拥有一些功能,让用户可以无限期地检查他们是否希望保持记录状态(从现在起3个月内任意设置cookie过期)。

我处理这个问题的代码是

private static HttpCookie GetFormsAuthenticationCookie(string userNameResponse, 
                                                        bool persistCookie)
{            
    var cookie = FormsAuthentication.GetAuthCookie(userNameResponse, persistCookie);

    if (persistCookie)
        cookie.Expires = DateTime.Now.AddMonths(3);

    return cookie;
}

private void LoginUser(string userNameResponse, bool PersistCookie)
{
    Response.Cookies.Add(GetFormsAuthenticationCookie(userNameResponse, PersistCookie));

    string navigateAfterUrl = FormsAuthentication.GetRedirectUrl(userNameResponse,
                                                                 PersistCookie);

    Response.Redirect(navigateAfterUrl);
}

但是稍后当我返回网站时,我需要再次登录。我已经验证了cookie在我的到期日期回来了,并且没有设置为会话cookie(也通过关闭/重新打开浏览器测试并且cookie仍然存在)。我的一个想法是它与ASP.NET到期时有关。

我的web.config中有一个特定的机器密钥设置,所以如果IIS重新启动等,不应该使用相同的cookie吗?有没有人有任何建议可以导致这个或至少如何进一步追踪这个,因为我想不出任何其他事情。

有帮助吗?

解决方案

当您致电 GetAuthCookie 方法时 FormsAuthenticationTicket = webweconfig中的“http://weblogs.asp.net/scottgu/archive/2005/11/08/430011.aspx"rel =”nofollow noreferrer“>超时属性。所以一定要正确设置:

<authentication mode="Forms">
  <forms
    loginUrl="/someloginUrl"
    requireSSL="true"
    protection="All"
    // This is the setting you are looking for! (it's in seconds)
    timeout="120"
    domain="example.com"
    slidingExpiration="false"
    name="cookieName" />
</authentication>

一旦票证被加密,它就被用作cookie的值。当您设置 Expires 属性时cookie到给定值,这表示它将在给定时间段内持久保存在客户端计算机上。然后在每个请求ASP.NET运行时将检查cookie的存在,将尝试解密该值并获取票证。接下来,它将使用Timeout属性检查故障单是否仍然有效,因此如果您的暂停时间很短,则无论您的cookie是否仍在传输,故障单都不再有效,并且身份验证将失败。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top