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

时间:2017-12-15 09:12:12

标签: 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
        };
    }

,这是从我的GetProfileDataAsync

调用的
if (context.RequestedClaimTypes.Any())
        {
            var user = UserClient.FindByUserName(context.Subject.GetSubjectId());
            if (user != null)
            {
                context.AddRequestedClaims(UserClient.GetUserClaims(user.Result.User));
            }
        }

当我调用/ connect / userinfo端点时,我得到了这个(没有角色):

  

{ “名称”: “joe3”, “GIVEN_NAME”: “乔”, “FAMILY_NAME”: “三”, “分”: “joe3”}

1 个答案:

答案 0 :(得分:2)

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

  1. 将Role的新Identity资源添加到返回的列表中 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}}
        };
    }
    
  2. 将角色范围添加到客户端的AllowedScopes列表

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

          "RequestedScopes": "openid profile email roles",
    
相关问题