System.Threading.Thread.CurrentPrincipal vs. System.Web.HttpContext.Current.User or why FormsAuthentication can be subtle
Warning: I find this fascinating and amazing as a caused a suble bug and was generally bizarre today. You likely don't care. :)
I have some code in an ASP.NET custom FormsAuthentication Login that looks something like this:
// This principal will flow throughout the request.
VoyagerPrincipal principal = new VoyagerPrincipal(yada, yada, yada);// Attach the new principal object to the current HttpContext object
HttpContext.Current.User = principal;
It it called on the Global.asax's AuthenticateRequest so everything is all setup before the Page's events fire. It provides a custom IPrincipal that integrates our eFinance Server with ASP.NET. It's quite a lovely subsystem, IMHO.
Other operations count on being able to get this 'Call Context' IPrincipal from the current thread at any time. In another section of code someone was doing this in the MIDDLE of the HttpRequest (somewhere in the Page_Load) after having JUST called the routine above for the first time:
return Thread.CurrentPrincipal as VoyagerPrincipal;
Assuming, of course that the Thread's CurrentPrincipal is that same Principal. And 99.999% percent of the time it is, except when it isn't at all.
In the instance where someone calls the first chunk of code then expects to be able to call the second chunk within the same HttpRequest, the Thread.CurrentPrincipal contains a GenericPrincipal populated much earlier by the HttpApplication. (Or a WindowsPrincipal, depending on your settings).
- When the first chunk of code runs in the Global.asax's AuthenticateRequest these two properties ARE in fact the same object
- When the first chunk of code runs in the context of a Page (read: later!) these properties are NOT the same object.
Why? Reflector tells us in the HttpApplication's internal OnThreadEnter:
internal void OnThreadEnter()
{
this._savedContext = HttpContextWrapper.SwitchContext(this._context);
this._context.Impersonation.Start(false, true);
HttpRuntime.RequestTimeoutManager.Add(this._context);
this.SetPrincipalOnThread(this._context.User);
this.SetCulture(false);
}internal void SetPrincipalOnThread(IPrincipal principal)
{
if (!this._restorePrincipal)
{
this._restorePrincipal = true;
this._savedPrincipal = Thread.CurrentPrincipal;
}
Thread.CurrentPrincipal = principal;
}
I had assumed, wrongly, that these two objects were coming from the same object reference always. In fact, they are early on, but you can (as I did) change one without changing the other. So, the first chunk of code becomes this:
// This principal will flow throughout the request.
VoyagerPrincipal principal = new VoyagerPrincipal(yada, yada, yada);// Attach the new principal object to the current HttpContext object
HttpContext.Current.User = principal;// Make sure the Principal's are in sync
System.Threading.Thread.CurrentPrincipal = System.Web.HttpContext.Current.User;
And all is right with my world, and the folks can continue to get the expected behavior when doing a "mid-page" FormAuthentication login.
About Scott
Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.
About Newsletter
Another caveat.
You said "When the first chunk of code runs in the Global.asax's AuthenticateRequest these two properties ARE in fact the same object". This isn't entirely true.
When you set the HttpContext.Current.User to your custom IPrincipal in the Global.asax AuthenticateRequest, the Thread.CurrentPrincipal is still the Generic/Windows principal set in the HttpApplication.OnThreadEnter. So if any other method tries to pull out your custom IPrincipal *during* the AuthenticateRequest, they will be in for a suprise. (We hit this exact scenario ourselves). I'll have to do a little more research, but basically sometime after the Global.asax AuthenticateRequest, but before the Page is called, ASP.NET sets the Thread.CurrentPrincipal to the same principal as HttpContext.Current.User. Meaning that your statement is true sometime *after* AuthenticateRequest.
Lesson: Even in Global.asax AuthenticateRequest, set both HttpContext.Current.User and Thread.CurrentPrincipal to your custom IPrincipal.
JasonL
Peter: could you clarify/point to additional info?
However, I don't understand what Peter is saying. ASP.NET is going to set that Thread's Current Principal "after AuthenticateRequest" anyway (using the same line of code) so why are you (Peter) saying never to do that?
Additional thought: Perhaps in EndRequest or somewhere this Principal should be blown away (or is it already) for security reasons?
To your additional thought, Scott: I don't know if this is what you're asking, but check out HttpApplication.OnThreadLeave(). This calls RestorePrincipalOnThread, which sets Thread.CurrentPrincipal back to whatever it was before. As for the custom principal, at that point there are no more references to it so it's "floating" around on the heap waiting to be GC'd. (unless a reference is stashed in session etc. which would probably be bad idea).
I also agree with you Jason, I'm just moving up the assignment to an earlier point, although as you point out, it will get blown away in the RestorePrincipalOnThread so my security concerns aren't a problem.
This is one where if you don't know the pipeline, it's just maddening to try and figure out what's going on. There are still many subtle inconsistencies, too...
http://weblogs.threepines.net/taba/archive/2004/09/10/270.aspx
My conclusion so far is that I've yet to find any evidence to back up Peter's claim.
I believe the missing element to this conversation is the fact that the HttpContext.Current.User and the Thread.CurrentPrincipal have very different purposes. It is very acceptible and common for the Current.User and CurrentPrincipal to be different - it's called delegation. Delegation, in my experience, is used most when an application requires Sql Server connections, widnows authentication, and trusted connections. This is because connection pooling is not as effective under these connections.
Anyways, take a look at the system.web's identity element for more information. In general, setting the CurrentPrincipal is going to be reserved for WinForm application delegation, which tends to be rare itself. Whoever is attempting to get the custom principal from the Thread.CurrentPrincipal should be informed that user context should be gathered from the HttpContext.
Comments are closed.
You just found the famous TLS bug :)
http://www.hanselman.com/blog/PermaLink.aspx?guid=320
Some information can be found in that link too.
The main point: You should NEVER do this:
System.Threading.Thread.CurrentPrincipal = System.Web.HttpContext.Current.User;
Peter