【问题标题】:How include roleclaim to accesstoken?如何将角色声明包含到访问令牌中?
【发布时间】:2019-04-12 10:07:23
【问题描述】:

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

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

【问题讨论】:

标签: c# asp.net-identity identityserver4


【解决方案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
    }
}

【讨论】:

  • Tnx。这就是我一直在寻找的。​​span>
猜你喜欢
  • 2019-09-13
  • 2018-02-07
  • 2017-03-23
  • 2021-03-19
  • 2021-12-27
  • 2020-12-25
  • 1970-01-01
  • 2019-06-21
  • 2023-01-11
相关资源
最近更新 更多