开发者

Invalidating ASP.NET FormsAuthentication server side

I am experimenting with FormsAuthentication (using ASP.NET MVC2) and it is working fairly well.

However, one case I can't work out how to deal with is validating the user identity on the server to ensure it is still valid from the server's perspective.

eg.

  1. User logs in ... gets a cookie/ticket
  2. Out of band the user is deleted on the server side
  3. User makes a new request to the server. HttpContext.User.Identity.Name is set to the deleted user.

I can detect th开发者_运维问答is fine, but what is the correct way to handle it? Calling FormsAuthentication.SignOut in the OnAuthorization on OnActionExecuting events is too late to affect the current request.

Alternatively I would like to be able to calls FormsAuthentication.InvalidateUser(...) when the user is deleted (or database recreated) to invalidate all tickets for a given (or all) users. But I can't find an API to do this.


In the global.asax, add an handler for AuthenticateRequest. In this method, the forms authentication has already taken place and you're free to modify the current principal before anything else happens.

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;
  }     
}

Just implement the UserStillValid method and you're done. It's also a good place to swap the generic principal with a custom one if you need to.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜