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?
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 .
ClaimTypes. NameIdentifier gives the current user id, and ClaimTypes.Name gives the username.
string username = currentUser. UserName; //Get UserId of Currently logged in user.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With