我正在根据我之前的问题和答案实现身份验证超时检测机制here。我已经实现了一个 HTTP 模块,该模块使用 AuthenticateRequest 事件来运行代码来捕获身份验证期限是否已过期。执行此操作的代码如下:
public class AuthenticationModule : IHttpModule
{
#region IHttpModule Members
void IHttpModule.Dispose() { }
void IHttpModule.Init(HttpApplication application)
{
application.AuthenticateRequest += new EventHandler(this.context_AuthenticateRequest);
}
#endregion
/// <summary>
/// Inspect the auth request...
/// </summary>
/// <remarks>See "How To Implement IPrincipal" in MSDN</remarks>
private void context_AuthenticateRequest(object sender, EventArgs e)
{
HttpApplication a = (HttpApplication)sender;
HttpContext context = a.Context;
// Extract the forms authentication cookie
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = context.Request.Cookies[cookieName]; // no longer a forms cookie in this array once timeout has expired
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
DateTime expirationTime = authTicket.Expiration;
// check if previously authenticated session is now dead
if (authTicket != null && authTicket.Expired)
{
// send them a Response indicating that they've expired.
}
}
}
}
问题是,一旦身份验证期限到期(我将其设置为 1 分钟进行测试),就不再有表单 cookie(请参阅代码中的注释)。这意味着身份验证 cookie 将为空,并且我不会让它通过代码中的空检查。但是 FormsAuthenticationTicket 有一个方便的“Expired”属性,我觉得我应该检查该期限是否已过期。但如果 cookie 不再存在,我该如何做到这一点呢?如果不再有表单 cookie,那么假设身份验证期限已过期是否合理?
对此有任何帮助将不胜感激。
您可能想尝试这样的事情:
if (User != null)
{
FormsIdentity id = (FormsIdentity)User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;
if (ticket.Expired)
{
//do something
}
}
更多信息
Edit:
1:我看到用户将为空。所以使用 User.Identity 是没有问题的。
2:在 BeginRequest 事件中尝试原始问题中的代码而不是 AuthenticateRequest 怎么样。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)