我已经像这样覆盖了用户声明的主要工厂:
public class CustomClaimsPrincipalFactory : UserClaimsPrincipalFactory<User, Role>
{
public CustomClaimsPrincipalFactory(UserManager<User> userManager, RoleManager<Role> roleManager,
IOptions<IdentityOptions> optionsAccessor)
: base(userManager, roleManager, optionsAccessor)
{
}
protected override async Task<ClaimsIdentity> GenerateClaimsAsync(User user)
{
var id = await base.GenerateClaimsAsync(user);
id.AddClaim(new Claim(ClaimTypes.Email, user.Email));
return id;
}
}
并且还将工厂添加到我的身份配置中,如下所示:
services.AddIdentityMongoDbProvider<User, Role>(identityOptions =>
{
identityOptions.Password.RequiredLength = 6;
identityOptions.Password.RequireLowercase = false;
identityOptions.Password.RequireUppercase = false;
identityOptions.Password.RequireNonAlphanumeric = false;
identityOptions.Password.RequireDigit = false;
}, mongoIdentityOptions => {
mongoIdentityOptions.ConnectionString = configuration["Data:DefaultConnection:ConnectionString"];
}).AddClaimsPrincipalFactory<CustomClaimsPrincipalFactory>();
如果我在我的GenerateClaimsAsync方法中添加一个断点,我可以看到它按原样添加了声明(以某种方式将声明添加了10次,甚至只打了一次方法)。
稍后,当我想提出一项索赔时,我会这样做:
protected string GetUsername()
{
if (User != null && User.HasClaim(claim => claim.Type.Equals(UserClaims.UserName)))
{
var claimValue = User.Claims.SingleOrDefault(w => w.Type == UserClaims.UserName);
return claimValue?.Value;
}
throw new HttpException(HttpStatusCode.Unauthorized);
}
这里的用户属于ClaimsPrincipal类型,该对象看起来像是我向其添加了声明的对象,但是该对象中的任何地方都没有声明。
这是我用来登录的代码:
public async Task<UserDto> Login(LoginDataContract dataContract)
{
var appUser = userManager.Users.SingleOrDefault(s => s.Email == dataContract.Email);
var result = await signInManager.PasswordSignInAsync(dataContract.Email, dataContract.Password, false, false);
if (result.Succeeded)
{
var jwtObject = AuthenticationHelper.GenerateJwtToken(dataContract.Email, appUser, appSettings);
var userDto = mapper.Map<User, UserDto>(appUser);
userDto.Token = jwtObject.token;
userDto.TokenExpiresIn = jwtObject.expiresIn;
return userDto;
}
throw new Exception("Failed to login!");
}
索赔为何不成立?