Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 871
Firoso Avatar asked Mar 06 '13 18:03

Firoso


People also ask

How can get current user in ASP NET MVC?

If you need to get the user from within the controller, use the User property of Controller. If you need it from the view, I would populate what you specifically need in the ViewData , or you could just call User as I think it's a property of ViewPage .

How do I get current user in .NET core?

ClaimTypes. NameIdentifier gives the current user id, and ClaimTypes.Name gives the username.

Which string is used to obtain the user name of the current user inside an ASP NET MVC web application?

string username = currentUser. UserName; //Get UserId of Currently logged in user.


1 Answers

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

like image 72
granadaCoder Avatar answered Sep 28 '22 18:09

granadaCoder