2011-06-18 33 views
0

我有一个asp.net mvc 3网站,拥有我自己的授权属性。当我在用户登录进行形式验证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> 

回答

3

要创建一个使用一个cookie 30分钟超时:

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

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

如果你要匹配你的web.config值,你可以使用以下命令:

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