10

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 this 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.

Rob Walker
  • 46,588
  • 15
  • 99
  • 136

1 Answers1

7

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.

Scott Rippey
  • 15,614
  • 5
  • 70
  • 85
Julien Lebosquain
  • 40,639
  • 8
  • 105
  • 117
  • UserStillValid function will check the user is active in db or not? what is the meaning of Thread.CurrentPrincipal = anonymousPrincipal and HttpContext.Current.User = anonymousPrincipal; – Thomas Sep 03 '15 at 09:55