views:

85

answers:

1

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.

+1  A: 

In the global.asax, add an handler for AuthentificationRequest. 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.

Julien Lebosquain