MVC 5 with ASP.NET Identity - Get Claims when user logs in

回眸只為那壹抹淺笑 提交于 2019-12-23 11:09:11

问题


I am using OWIN 2.0, and after I log in a user, I want to retrieve an existing claim from the database but if I try to get the user's claims they are empty. If I put the same code in any of the subsequent controllers that gets called then the claims are there. It seems that the claims are not available until the next request after the initial login. Why is this?

var claimsIdentity = User.Identity as ClaimsIdentity;
var testClaim = claimsIdentity.Claims.Where(r => r.Type == "TestClaim").FirstOrDefault();

回答1:


Possibly because you haven't passed the claims into the initial login (or have missed calling CreateIdentityAsync)?

With an out-of-the-box MVC5 application, I do this in the SignInAsync method:

private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
    var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

    //Get the given name from somewhere
    var givenName = GetGivenName();

    identity.AddClaim(new Claim(ClaimTypes.GivenName, givenName));

    AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}

And this is called from the Login action.



来源:https://stackoverflow.com/questions/23926205/mvc-5-with-asp-net-identity-get-claims-when-user-logs-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!