How to set Thread.CurrentPrincipal for use throughout the application?

asp.net, authentication, identity, principal

Solution

You can handle FormsAuthentication_OnAuthenticate(object sender, FormsAuthenticationEventArgs e) (in Global.asax) and set CurrentPrincipal here.

void FormsAuthentication_OnAuthenticate(object sender, FormsAuthenticationEventArgs e)
{
var phoenixIdentity = new PhoenixIdentity("B", "Forms" , true);
var principal = new PhoenixPrincipal(phoenixIdentity);
e.User = principal;
}

Problem

In an ASP.net application I'm using a Login control with a custom membership provider that I wrote. What I want to do is to set `Thread.CurrentPrincipal` to my custom Principal object, just after the user is authenticated. I'm using the setter: `Thread.CurrentPrincipal` and it sets the Principal object for me but, on all the consequent threads this CurrentPrincipal is overridden with the default one. Here is my code for the Authenticate event of the Login control: ``` protected void Login1_Authenticate(object sender, AuthenticateEventArgs e) { string username = Login1.UserName; string password = Login1.Password; if (Membership.ValidateUser(username, password)) { var login = sender as Login; var phoenixIdentity = new PhoenixIdentity("B", "Forms" , true); var principal = new PhoenixPrincipal(phoenixIdentity); Thread.CurrentPrincipal = principal; AppDomain.CurrentDomain.SetThreadPrincipal(principal); HttpContext.Current.User = principal; e.Authenticated = true; } } ``` For example, imagine that I login with the username A, everything goes well... Validation passes, but I hardcode the user with the username B in the Identity object which is set to the Principal object I set as the `CurrentPrincipal` object. When I check which user is set to the `CurrentPrincipal` Identity at the end of this method it says it's user B. But when I load another page and then check what the Identity of the `CurrentPrincipal` is, it says it's user A. So, how can I make my `CurrentPrincipal` object to be persistent across all other threads, and where/when does this Login control set the `CurrentPrincipal` object of the Thread?

Original source