in ASP.NET how can I set the current User Identity for the session?

asp.net, asp.net-mvc, asp.net-mvc-4

Solution

Short Answer:

//
// Swapped FormsIdentity principal with our own custom IPrincipal
//
HttpContext.Current.User = yourPrincipalFromSomewhere;

//see
//http://www.hanselman.com/blog/SystemThreadingThreadCurrentPrincipalVsSystemWebHttpContextCurrentUserOrWhyFormsAuthenticationCanBeSubtle.aspx

//
// Sync Context Principal with Thread Principal
//
System.Threading.Thread.CurrentPrincipal = System.Web.HttpContext.Current.User;

So on the login, my team would put the IPrincipal (our custom one) here:

HttpContext.Current.Cache.Insert

And then on in the

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
}

we would grab it from the :

HttpContext.Current.Cache

and then reattach it to the :

// Swapped FormsIdentity principal with our own IPrincipal
                            //
                            HttpContext.Current.User = cachedPrincipal;

                            //see
                            //http://www.hanselman.com/blog/SystemThreadingThreadCurrentPrincipalVsSystemWebHttpContextCurrentUserOrWhyFormsAuthenticationCanBeSubtle.aspx

                            //
                            // Sync Context Principal with Thread Principal
                            //
                            System.Threading.Thread.CurrentPrincipal = System.Web.HttpContext.Current.User;

Am I saying "do it exactly like my team did"? Not necessarily. But I'm showing you the 2 places we came across to attach it.

And the hanselman link, which shows some info about it.

http://www.hanselman.com/blog/SystemThreadingThreadCurrentPrincipalVsSystemWebHttpContextCurrentUserOrWhyFormsAuthenticationCanBeSubtle.aspx

Problem

I've got a simple page, and I have a login button. I simply want to programmatically set the User identity so that when I re-navigate to this page or any other I can get the current User identity. Are there special considerations for this?

Original source