如何将角色声明包括在访问令牌中?

时间:2019-04-12 10:07:23

标签: c# asp.net-identity identityserver4

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

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

1 个答案:

答案 0 :(得分:1)

我回答了here,如何在访问令牌中包含角色。如果要另外包含角色声明,则需要使用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
    }
}