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.
source share