ASP.NET MVC WEB API Impersonation Thread issue

In an ASP.NET MVC WEB API application I implemented Windows Authentication with custom roles by using an implementation of IIdentity.
In my setup the user gets authenticated by NTLM, then we have the user name. Now there is a part in the OWIN Pipeline which gets the roles for this user and caches them.

When the user sends a request to the server it will go trough the “Application_OnPostAuthenticateRequest“method in the Global.asax.cs, this method will then get the User from the current thread (which is the authenticated user) and then create a new object of our custom implementation of IIdentity. After this we map some things like the UserName and get the correct roles for this user and append them.

The important part in the “Application_OnPostAuthenticateRequest” method is to set the modified Thread.CurrentPrincipal back to the HttpContext.Current.User. If you don’t do this, you possible lose our custom Identity object next time ASP.NET maps/sets the HttpContext.Current.User to Thread.CurrentPrincipal (Thread.CurrentPrincipal gets overriden by HttpContext.Current.User).

In my tests the ManagedThreadId in OnPostRequest method and the actual service operations where different, but not everytime. When I attach a debugger it worked. This leaded me to a threading problem. In the OnPostRequest method I set the Thread.CurrentUser and in my service operation I was in a different thread, that’s why the custom roles disappeared.

 

Maybe you have the some problem and this helps you :)


Posted Sep 20 2016, 04:53 PM by Holger Vetter
Filed under: , ,
developers.de is a .Net Community Blog powered by daenet GmbH.