我创建了identityserver4项目,并尝试在用户登录后添加更多声明。这是我的代码
false
但是,当我在需求处理程序中调用我的api时,我没有看到我对用户的声明,尽管我的用户ID在那里。添加用户声明的适当方法是什么?
答案 0 :(得分:1)
必须将声明添加到响应上下文中。如果您使用的是aspnetidentity,那么以下方法将适用于您
确保包含ProfileService实现并在ConfigureServices
连接到IdentityServer .AddProfileService<ProfileService>();
private readonly IUserClaimsPrincipalFactory<ApplicationUser> claimsFactory;
在GetProfileDataAsync中,您可以添加新版权声明
/// <summary>
/// This method is called whenever claims about the user are requested (e.g. during token creation or via the userinfo endpoint)
/// </summary>
/// <param name="context">The context.</param>
/// <returns></returns>
public override async Task GetProfileDataAsync(ProfileDataRequestContext context)
{
var sub = context.Subject.GetSubjectId();
var user = await userManager.FindByIdAsync(sub);
var principal = await claimsFactory.CreateAsync(user);
//context.AddFilteredClaims(principal.Claims);
context.IssuedClaims.AddRange(principal.Claims);
context.IssuedClaims.Add(new Claim("IP Address", coreOperations.GetCurrentRequestIPAddress()));
}
答案 1 :(得分:1)
正如Jay所述,您可以编写自己的ProfileService。如果您不使用aspnetidentity,则只需在Login方法中添加Claims并将这些行添加到ProfileService的GetProfileDataAsync方法:
List<Claim> claims = context.Subject.Claims.Where(x => x.Type == JwtClaimTypes.Role).ToList();
context.IssuedClaims.AddRange(claims);