具有ASP.NET身份的MVC 5-用户登录时获取声明 [英] MVC 5 with ASP.NET Identity - Get Claims when user logs in
问题描述
我正在使用OWIN 2.0,登录用户后,我想从数据库中检索现有的声明,但是如果尝试获取用户的声明,则它们为空.如果我将相同的代码放在随后被调用的任何控制器中,那么声明就在那里.似乎直到首次登录后的下一个请求,这些声明才可用.为什么是这样?
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();
推荐答案
可能是因为您尚未将声明传递到初始登录名中(或者错过了呼叫CreateIdentityAsync
的原因)?
Possibly because you haven't passed the claims into the initial login (or have missed calling CreateIdentityAsync
)?
对于现成的MVC5应用程序,我可以在SignInAsync
方法中执行此操作:
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);
}
这是从Login
动作中调用的.
这篇关于具有ASP.NET身份的MVC 5-用户登录时获取声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!