ASP.NET Authentication sliding expiry time on cust

2019-02-04 16:17发布

I am creating my own authentication ticket using the following code:

string formsCookieStr = string.Empty;
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
            1,                              // version
            username,                       // user name
            DateTime.Now,                   // issue time
            DateTime.Now.AddMinutes(30),    // expires
            false,                          // Persistence
            userRoleData                    // user data
    );
formsCookieStr = FormsAuthentication.Encrypt(ticket);
HttpCookie FormsCookie = new HttpCookie(FormsAuthentication.FormsCookieName, formsCookieStr);
HttpContext.Response.Cookies.Add(FormsCookie);

I want the expiration to be a sliding expiration - each time the client sends a request then the expiration should be reset to 30 mins. However, I'm only creating the ticket when the user first logs in. Will ASP.NET automatically keep sliding the expiry time for me, or do I need to do something 'manually' to implement the sliding expiration?

1条回答
再贱就再见
2楼-- · 2019-02-04 16:57

That's configured in the forms section of web.config. The way sliding expiration works is that on each request the ASP.NET engine rewrites the authentication cookie by incrementing the timeout:

<authentication mode="Forms">
  <forms 
      loginUrl="~/Account/LogOn" 
      timeout="2880" 
      slidingExpiration="true" 
  />
</authentication>

Note however that enabling sliding expiration is one of the things considered as bad practice in the ASP.NET Security Practices.

查看更多
登录 后发表回答