使ASP.NET FormsAuthentication服务器端无效

时间:2010-05-23 20:32:34

标签: asp.net forms-authentication

我正在尝试使用FormsAuthentication(使用ASP.NET MVC2)并且它运行得相当好。

然而,我无法解决的一个案例是验证服务器上的用户身份,以确保它从服务器的角度来看仍然有效。

例如

  1. 用户登录...获取Cookie /票证
  2. 带外用户在服务器端被删除
  3. 用户向服务器发出新请求。 HttpContext.User.Identity.Name设置为已删除的用户。
  4. 我可以检测这个很好,但处理它的正确方法是什么?在FormsAuthentication.SignOut OnAuthorization事件中调用OnActionExecuting为时已晚,无法影响当前请求。

    或者,我希望能够在删除用户(或重新创建数据库)时调用FormsAuthentication.InvalidateUser(...),以使给定(或所有)用户的所有票证无效。但我找不到这样做的API。

1 个答案:

答案 0 :(得分:7)

在global.asax中,为AuthenticateRequest添加处理程序。在此方法中,表单身份验证已经发生,您可以在其他任何事情发生之前自由修改当前主体。

protected void Application_AuthenticateRequest(object sender, EventArgs e) {
  IPrincipal principal = HttpContext.Current.User;
  if (!UserStillValid(principal)) {
    IPrincipal anonymousPrincipal = new GenericPrincipal(new GenericIdentity(String.Empty), null);
    Thread.CurrentPrincipal = anonymousPrincipal;
    HttpContext.Current.User = anonymousPrincipal;
  }     
}

只需实施UserStillValid方法就可以了。如果需要,它也是将通用主体与自定义主体交换的好地方。