what is the benefit of adding UserClaims 'role' to IdentityResource

Viewed 1724

why we add , or what the benefit of adding UserClaims 'role' to IdentityResource

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

it's not add the roles to the token

i can only add the roles to token by adding UserClaims 'role' to ApiResource

when i remove UserClaims 'role' from IdentityResource my project also work fine.

1 Answers

The 'UserClaims' that are identified would be required for a user to have in their identity token when they try to use the particular resource.

If this resource was an API and you had the UserClaim 'Admin' defined.

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

The API methods would not be able to be used unless the user had the 'Admin' claim.

IdentityServer4 Documentation.

UPDATE:

JwtClaimTypes.Role is a common claim type or group. I don't think it would be common to have a claim value of 'role' in the claims type of JwtClaimTypes.Role.

See the following example: (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"));
        }
Related