我错过了什么?“我的表单超时”不会使会话超时

本文关键字:超时 会话 表单 什么 错过了 我的 | 更新日期: 2023-09-27 17:59:49

我有一个asp.net mvc 3网站,它有我自己的authorize属性。当用户登录时,我制作一个表单Auth cookie

 public void SetAuthCookie(string userName, string userData = "",int version = 1)
    {
        DateTime expiry = DateTime.UtcNow.AddMinutes(30);
        FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(version, userName, DateTime.UtcNow, expiry, false, userData, "/");
        string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
        HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket) {Path = "/"};
        HttpContext.Current.Response.Cookies.Add(authCookie);
    }

//AuthorizeAttribute

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
       if (httpContext == null)
        {
            throw new ArgumentNullException("httpContext");
        }

       if (httpContext.User.Identity.IsAuthenticated)
       {
          return true;
       }
        return false;
    }

所以我去我的网站登录,等待我的网站超时。然后我做一个请求(这是一个ajax请求),它首先通过我的属性,httpContext.User.Identity.IsAuthenticated仍然设置为true,尽管我在3分钟内没有向服务器请求

  <authentication mode="Forms">
      <forms loginUrl="~/Account"
                      protection="All"
                      name=".MySite"
                      path="/"
                      requireSSL="false"
                      slidingExpiration="true"
                      defaultUrl="default.aspx"
                      cookieless="UseDeviceProfile"
                      enableCrossAppRedirects="false"
                       timeout="1"
                       />
    </authentication>

我错过了什么?“我的表单超时”不会使会话超时

您正在创建一个超时30分钟的cookie:

DateTime expiry = DateTime.UtcNow.AddMinutes(30);

因此,您必须等待30分钟,此cookie才会失效。您在web.config中指定的1分钟超时将被忽略,因为您正在手动创建超时为30分钟的cookie。

如果您想匹配web.config中的值,可以使用以下内容:

DateTime expiry = DateTime.UtcNow.AddMinutes(FormsAuthentication.Timeout);

我同意以上答案

查看更多详细信息http://weblogs.asp.net/owscott/archive/2006/07/15/Forms-Authentication-Timeout.aspx

这可能有助于