ASP.NET Authentication sliding expiry time on custom ticket

淺唱寂寞╮ 提交于 2020-01-10 10:28:06

问题


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:


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.



来源:https://stackoverflow.com/questions/6275915/asp-net-authentication-sliding-expiry-time-on-custom-ticket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!