Thread.CurrentPrincipal set in Application_AuthenticationRequest is not set later in the app

StackOverflow https://stackoverflow.com/questions/809727

  •  03-07-2019
  •  | 
  •  

Question

In the global.asax file for the Application_AuthenticationRequest I'm setting the Thread.CurrentPrincipal to a custom principal. I also set the HttpContext.Current.User to the same principal.

However later in the app when I need to cast the Thread.CurrentPrincipal to our custom type, I get a runtime error saying: Unable to cast object of type 'System.Web.Security.RolePrincipal' to type 'OurCustomPrincipal'.

How did the Thread.CurrentPrincipal get reset to RolePrincipal, and more to the point how do I keep it at the CustomPrincipal we set in the global.asax

Thanks in advance

Was it helpful?

Solution

You surely have resolved your problem by now but just in case, if you are using the RoleProvider from ASP.NET, the RoleManagerModule overwrites the GenericPrincipal object created by the FormsAuthenticationModule and replaces it with a RolePrincipal object during the PostAuthenticateRequest: http://www.asp.net/Learn/Security/tutorial-11-vb.aspx

OTHER TIPS

To sum up, a quick fix is to perform your principal and identity replacements on the Application_OnPostAuthenticateRequest handler instead.

Please verify that you have implemented a class for IIDentity & Iprincipal interface and then you are using something like the following code to assign the currentprincipal.

    Dim userIdentity As CustomIdentity
    userIdentity = New CustomIdentity(username, True,"forms", sessionId)

    Dim principal As New CustomPrincipal(userIdentity, arrRoles)
    HttpContext.Current.User = principal
    System.Threading.Thread.CurrentPrincipal = principal
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top