Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 885
Rob Walker Avatar asked May 23 '10 20:05

Rob Walker


1 Answers

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.

like image 117
Julien Lebosquain Avatar answered Oct 06 '22 04:10

Julien Lebosquain