I am looking for a way to ensure that Thread.CurrentPrincipal reflects the ClaimsPrincipal we create during claims transformation.
We are building a system in which the ASP.NET Web API controllers are part of a thin interface layer on top of our business logic layer. We envision other interface layer modules, side-by-side with the ASP.NET Web API REST interface, also providing access
to the business logic layer. Not all of the interfaces will use HTTP.
The business logic layer is completely isolated from the transport that delivered the request. It does not know, or care, whether the request came via HTTP. The business layer must be able to create audit entries that identify the user that initiated the
request. It also must be able to perform additional authentication tests that might be more fine grained than those performed at the ASP.NET Web API controller level. Finally, it must be able to forward the requesting user’s identity to lower layers and
to other servers.
As far as I understand it, the traditional best practice for user identity to flow throughout an application is through
Thread.CurrentPrincipal. However, I’ve seen cautions about relying on
Thread.CurrentPrincipal in an ASP.NET Web API application.
Would it be safe to rely on Thread.CurrentPrincipal throughout all layers and threads of my application if, in our Claims Transformation middleware, we take the initial principal from
HttpContext.Current.User, and then assign the transformed principal to both
Thread.CurrentPrincipal and HttpContext.Current.User?
The various web frameworks are moving away from static variables such as HttpContext.Current (and similarly Thread.CurrentPrincipal) as they are problematic with unit testing as well as the thread switching that occurs with async code. The recommendation
is to pass the ClaimsPrincipal as a formal parameter to your APIs.
Thank you for the reply, Brock!
It sounds like there are more subtle issues with thread switching than I knew to be concerned about. Can you (or anyone) point me at any additional information, so that I can get up to speed on them?
Thanks VERY much,
I don’t have any articles but you can see the move this way — in ASP.NET vNext they removed HttpContect.Current. Maybe search for David Fowler on this forum as I’m sure he’s mentioned it in some of his posts discussing vNext.
Thanks for your post.
Please check this article :
#System.Threading.Thread.CurrentPrincipal vs. System.Web.HttpContext.Current.User or why FormsAuthentication can be subtle
Maybe it will help you.