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

In an ASP.net application, I use the Login control with a custom membership provider that I wrote. What I want to do is install Thread.CurrentPrincipalPrincipal on my user object right after user authentication.

I use setter: Thread.CurrentPrincipaland it sets the Principal object for me, but in all subsequent threads the CurrentPrincipal is overridden by default.

Here is my code for the Login control Authenticate event:

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;
        }
    }

, , A, ... , B Identity, Principal, CurrentPrincipal .

, CurrentPrincipal Identity , , B. , , CurrentPrincipal, .

, CurrentPrincipal / Login CurrentPrincipal Thread?

+5
3

FormsAuthentication_OnAuthenticate ( , FormsAuthenticationEventArgs e) ( Global.asax) CurrentPrincipal.


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

Tadas , FormsAuthentication .

, , , URL-, , . , , .

FormsAuthentication,

  • , Auth Cookie ,
  • cookie, FormsAuthentication.SetAuthCookie
  • 1.
  • Auth Cookie ASP.NET differnet .
  • ASP.NET Global.asax , , , ,

, , , HTTP-, init AfterRequestAcquired, , .

+2

, FormsAuthentication_OnAuthenticate:

if (FormsAuthentication.CookiesSupported)
        {
            if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
            {
                try
                {
                    FormsAuthenticationTicket ticket = 
                        FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value);

                    var myIdentity = new GenericIdentity("B");
                    var principal = new GenericPrincipal(myIdentity, new string[]{"rola1"});
                    e.User = principal;
                }
                catch (Exception ex)
                {
                    // Decrypt method failed.
                }
            }
        }
        else
        {
            throw new HttpException("Cookieless Forms Authentication is not " +
                                    "supported for this application.");
        }

, , ... , / e.User, , ... , ...

+1

All Articles