Custom FormsAuthenticationTicket validation

2019-06-09 09:47发布

问题:

I've got a website that hosts many asp.net applications. Some of written in MVC2, some are written in MVC3, some are not written in house and binary deployed (although we can find source code) and many many more are written in ASP.Net 2.0 webforms. Across all of these sites we use a single login page from a login application. We can do this because all applications share:

  1. The same application pool
  2. The same machine key
  3. The same login cookie name

My problem is they also share the security problem, no cookie spoofing protection. My plan is to add some extra information (first 2 bytes of ip, user agent) to the login cookie (possibly in the useradata field) and then verify this on every request before accepting the cookie.

My question is where does asp.net check the forms authentication ticket and load the user and can I override this to check a few extra things before using the login.

It would be a plus if I didn't have to add this code to every global.cs and could put it in some dll and reference that dll in the config file.

回答1:

You can not override Authentication except by writing a new FormsAuthenticationModule, but there is a simpler way. while the ASP.NET pipeline processing requests, At each step, an event is raised, this is where you can tap into the ASP.NET pipeline and do your job.

In your case, you can validate your cookie in PostAuthenticateRequestHandler event handler.

 HttpCookie authCookie = Context.Request.Cookies["YourFormsCookieName"];
 if (IsValidAuthCookie(authCookie))
 {
   // do some stuff
 }
 else
 {
   // expire cookie using FormsAuthentication.Signout()
   // do some stuff
 }

this is a useful link: Forms Authentication