使ASP.NET FormsAuthentication服务器端无效

Rob*_*ker 10 asp.net forms-authentication

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

但是,我无法弄清楚如何处理的一个案例是验证服务器上的用户身份,以确保从服务器的角度来看它仍然有效.

例如.

  1. 用户登录...获取cookie /票证
  2. 带外用户在服务器端被删除
  3. 用户向服务器发出新请求.HttpContext.User.Identity.Name设置为已删除的用户.

我可以发现这很好,但处理它的正确方法是什么?呼吁FormsAuthentication.SignOutOnAuthorizationOnActionExecuting事件太晚影响当前请求.

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

Jul*_*ain 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;
  }     
}
Run Code Online (Sandbox Code Playgroud)

只需实施该UserStillValid方法即可完成.如果需要,它也是将通用主体与自定义主体交换的好地方.