Custom principal return to GenericPrincipal on new requests

I am trying to implement a user primary and user identifier on a .NET MVC website. I created a custom core class that inherits from IPrincipal and a custom identifier that inherits from IIdentity.

When a user logs in, I set both Thread.CurrentPrincipal and HttpContext.Current.User to my user principle. When I look through either the debugger, the values ​​are set with all the properties.

However, as soon as the request is completed, and I try and request any other pages, Thread.CurrentPrincipal and HttpContext.Current.User are of type System.Security.Principal.GenericPrincipal, and not my user principle.

Do I need to do something "extra" to get my custom core information out of a stream or HttpContext?

thanks

+4
source share
3 answers

The values ​​in Thread.CurrentPrincipal and HttpContext.Current.User not saved between requests, they are rebuilt with each request. The best place for you is probably in Global.asax; write a function with a prototype:

 void Application_PostAuthenticateRequest(object sender, EventArgs e) 

This should turn out to be caused after the user is authenticated for each request, which will allow you to establish the principle as you would like.

+6
source

The principle of redefinition in:

 protected void Application_PostAuthenticateRequest(object sender, EventArgs e) 

Instead

 protected void Application_AuthenticateRequest(object sender, EventArgs e) 

In Global.asax.cs I worked for me in an ASP web application

0
source

I would like to expand the accepted answer a little, I hope that I can save someone a little.

In my case, the main one I used contained statements that were populated from external service results, so I wanted to cache the results during login.

I created a simple cache interface, IUserPrincipalCache and registered it using MVC DependencyResolver . Upon entering the system, I create a principal and add it to the cache. (Since your implementation may be different, I will leave it all.)

Then I implemented this in Global.asax.cs :

 protected void Application_PostAuthenticateRequest(object sender, EventArgs e) { if (User.Identity.IsAuthenticated) { var cache = DependencyResolver.Current.GetService<IUserPrincipalCache>(); var claimsPrincipal = cache.FindUser(User.Identity.Name); if (claimsPrincipal != null) { Context.User = claimsPrincipal; Thread.CurrentPrincipal = claimsPrincipal; } } } 

I think it's important to point the check to IsAuthenticated , as in many cases I could bypass the cache check. You may also not need to update Thread.CurrentPrincipal , I think it depends on how you use it.

0
source

Source: https://habr.com/ru/post/1338291/


All Articles