添加UserClaims'角色'有什么好处?到IdentityResource

时间:2017-11-08 12:10:27

标签: identityserver4

为什么我们添加,或添加UserClaims'角色'到IdentityResource

new IdentityResource { Name = "role", UserClaims = new List<string> {"role"} }

它不会将角色添加到令牌

我只能通过添加UserClaims&#39;角色来将角色添加到令牌中。到ApiResource

当我删除UserClaims&#39;角色&#39;从IdentityResource我的项目也可以正常工作。

1 个答案:

答案 0 :(得分:1)

当用户尝试使用特定资源时,需要标识的'UserClaims'才能拥有其身份令牌。

如果此资源是API,并且您已定义UserClaim 'Admin'

new IdentityResource { 
           Name = "MyAPI", UserClaims = new List<string> {"Admin"} 
}

除非用户拥有'Admin'声明,否则无法使用API​​方法。

IdentityServer4 Documentation

<强>更新

JwtClaimTypes.Role是一种常见的声明类型或群组。我认为在'role'的声明类型中声明价值为JwtClaimTypes.Role是很常见的。

请参阅以下示例:(Source

        var claims = principal.Claims.ToList();

        claims = claims.Where(claim => context.RequestedClaimTypes.Contains(claim.Type)).ToList();


        claims.Add(new Claim(JwtClaimTypes.GivenName, user.UserName));
        //new Claim(JwtClaimTypes.Role, "admin"),
        //new Claim(JwtClaimTypes.Role, "dataEventRecords.admin"),
        //new Claim(JwtClaimTypes.Role, "dataEventRecords.user"),
        //new Claim(JwtClaimTypes.Role, "dataEventRecords"),
        //new Claim(JwtClaimTypes.Role, "securedFiles.user"),
        //new Claim(JwtClaimTypes.Role, "securedFiles.admin"),
        //new Claim(JwtClaimTypes.Role, "securedFiles")

        if (user.IsAdmin)
        {
            claims.Add(new Claim(JwtClaimTypes.Role, "admin"));
        }
        else
        {
            claims.Add(new Claim(JwtClaimTypes.Role, "user"));
        }

        if (user.DataEventRecordsRole == "dataEventRecords.admin")
        {
            claims.Add(new Claim(JwtClaimTypes.Role, "dataEventRecords.admin"));
            claims.Add(new Claim(JwtClaimTypes.Role, "dataEventRecords.user"));
            claims.Add(new Claim(JwtClaimTypes.Role, "dataEventRecords"));
            claims.Add(new Claim(JwtClaimTypes.Scope, "dataEventRecords"));
        }
        else
        {
            claims.Add(new Claim(JwtClaimTypes.Role, "dataEventRecords.user"));
            claims.Add(new Claim(JwtClaimTypes.Role, "dataEventRecords"));
            claims.Add(new Claim(JwtClaimTypes.Scope, "dataEventRecords"));
        }