如何在身份服务器中向userinfo端点添加角色

jaz*_*000 2 asp.net identityserver4

我一直在使用身份服务器快速入门应用程序,我想添加在调用userinfo端点时要返回的角色信息。

  public Claim[] GetUserClaims(UserServiceProxy.Dto.User user)

    {
        return new Claim[]
        {
            new Claim(JwtClaimTypes.Name, user.Username), 
            new Claim(JwtClaimTypes.Email, user.Email),
            new Claim(JwtClaimTypes.GivenName, user.Firstname),
            new Claim(JwtClaimTypes.FamilyName, user.Lastname),
            new Claim(JwtClaimTypes.Subject, user.Username),
            new Claim(JwtClaimTypes.Role, user.Role ?? "normal"), //have added this
        };
    }
Run Code Online (Sandbox Code Playgroud)

这是从我的GetProfileDataAsync调用的

if (context.RequestedClaimTypes.Any())
        {
            var user = UserClient.FindByUserName(context.Subject.GetSubjectId());
            if (user != null)
            {
                context.AddRequestedClaims(UserClient.GetUserClaims(user.Result.User));
            }
        }
Run Code Online (Sandbox Code Playgroud)

当我调用/ connect / userinfo端点时,得到以下信息(无作用):

{“ name”:“ joe3”,“ given_name”:“ Joe”,“ family_name”:“ Three”,“ sub”:“ joe3”}

jaz*_*000 5

没关系,我发现问题是我需要:

  1. 将角色的新身份资源添加到GetIdentityResources返回的列表中

    public static IEnumerable<IdentityResource> GetIdentityResources()
    {
        return new List<IdentityResource>
        {
            new IdentityResources.OpenId(),
            new IdentityResources.Profile(),
            new IdentityResources.Email(),
            new IdentityResource{Name = "roles", UserClaims={JwtClaimTypes.Role}}
        };
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 将角色范围添加到客户端的AllowedScopes列表中

    AllowedScopes = new List<string>
                {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    IdentityServerConstants.StandardScopes.Email,
                    "roles",
    
                },
    
    Run Code Online (Sandbox Code Playgroud)
  3. 在请求中,添加对角色范围的请求。

          "RequestedScopes": "openid profile email roles",
    
    Run Code Online (Sandbox Code Playgroud)