如何将roleclaim包含到accesstoken中?

How include roleclaim to accesstoken?

我使用 identityserver4 和 asp.net 身份保护我的 API。身份数据库具有表角色和角色声明。对于我的安全模型,我需要具有她角色声明的角色。我包括角色以访问令牌,但我不明白如何包括角色声明。

//Example of API with roles
new ApiResource("api1", "My API")
{
   UserClaims = new []{ "name", "role" }
}

我回答了 如何在访问令牌中包含角色。如果您想另外包含角色声明,则需要使用 RoleManager.

public async Task GetProfileDataAsync(ProfileDataRequestContext context)
{
    context.IssuedClaims.AddRange(context.Subject.Claims);

    var user = await _userManager.GetUserAsync(context.Subject);

    var roles = await _userManager.GetRolesAsync(user);

    foreach (var role in roles)
    {
        var roleClaims = await RoleManager.GetClaimsAsync(role);

        context.IssuedClaims.Add(new Claim(JwtClaimTypes.Role, role)); //Adds "role" claim
        context.IssuedClaims.AddRange(roleClaims); //Adds other role claims
    }
}