Devildog74 wrote:
brett, I am not sure what the blog is "really" saying. You could have issues with the IPrincipal object due to thread switching taking place behind the scenes in the ASP.NET Runtime?
Can you elaborate a bit?
I had to read it about 5 times and do some looking around with Reflector before I really figured it out!!
Here's how I understand it:
After the Application.AuthenticateRequest event is fired, ASP.NET runs the SetPrincipalOnThread method, which basically achieves this:
System.Threading.Thread.CurrentPrincipal = System.Web.HttpContext.Current.User
As this is happening right after the AuthenticateRequest event, any references to Thread.CurrentPrincipal hereafter in the application will return the custom principal object (Current.User).
However, when HttpContext.Current.User is set in a page, any code running later on (in the same request though) that accesses Thread.CurrentPrincipal will NOT be getting the custom principal contained in HttpContext.Current.User. This is because the Application.AuthenticateRequest event has not yet fired for the current request, and thus the ASP.NET runtime has not yet set System.Threading.Thread.CurrentPrincipal = System.Web.HttpContext.Current.User.
Before:
Request 1
1. Anonymous comes in, AuthenticateRequest does not fire
2. User logs in
3. HttpContext.Current.User set to MyCustomPrincipal
4. Code somewhere in app refers to Thread.CurrentPrincipal (this is currently whatever ASP.NET set it to, NOT MyCustomerPrincipal)
Request 2
1. Request comes in, and since HttpContext.Current.User is set, AuthenticateRequest fires
2. Thread.CurrentPrincipal is set to HttpContext.Current.User
3. Code somewhere in app refers to Thread.CurrentPrincipal, which is now the same as HttpContext.Current.User
After:
Request 1
1. Anonymous comes in, AuthenticateRequest does not fire
2. User logs in
3. HttpContext.Current.User set to MyCustomPrincipal
4. Thread.CurrentPrincipal is set to HttpContext.Current.User
5. Code somewhere in app refers to Thread.CurrentPrincipal (this is now a MyCustomerPrincipal instance)