您应该能够在表单身份验证 cookie 上定义到期日期,使其在创建后 30 分钟内到期(大概是在对您的应用进行访问时)。
我通常首先创建一个FormsAuthenticationTicket:
var ticket = new FormsAuthenticationTicket {
1, // a version number; do with it as you like
"my ticket name",
DateTime.Now, // set when the cookie is valid from
DateTime.Now.Add(FormsAuthentication.Timeout), // and when it expires
false, // is the cookie persistent?
"cookie data" // the actual "value" of the cookie;
// I normally put in sufficient stuff to recreate
// the principal + identity on request
};
// encrypt that
var token = FormsAuthentication.Encrypt(ticket);
然后您可以继续实际创建 cookie
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, token) {
// expiry, again (there must be something redundant here)
Expires = DateTime.Now.Add(FormsAuthentication.Timeout),
// add this if you need it
HttpOnly = true
};
// then flush that in with the response
HttpContext.Current.Response.Cookies.Add(cookie);
FormsAuthentication.Timeout 的值可以在您的web.config 中定义,也可以在您的代码中的某处进行设置。默认值为 30 分钟,因此如果您没有进行任何更改,应该没问题。
<system.web>
<!-- ... -->
<authentication mode="Forms">
<forms timeout="30" ... >
<!-- ... -->
</forms>
</authentication>
</system.web>
我觉得应该有一种更简单的方法来做到这一点,但我喜欢用上面的方法来处理(相对)细粒度的细节。那,或者我只是不必要地无知。
根据我的应用程序的需要,我可以通过制作一个专门作为一种 DTO 传递给FormsAuthenticationTicket 的类来为身份验证票证添加额外的验证。这里有相当多的灵活性供您利用。