Search code examples
asp.netidentityserver4

how to add role to userinfo endpoint in identity server


I have been using the identity server quick start application, and I want to add role information to be returned when I call the userinfo endpoint.

  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
        };
    }

and this is called from my GetProfileDataAsync

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

When I call the /connect/userinfo endpoint, I get this (no role):

{"name":"joe3","given_name":"Joe","family_name":"Three","sub":"joe3"}


Solution

  • Never mind, I discovered the problem was that I needed to:

    1. Add a new Identity resource for Role to the list returned by 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. Add the role scope to the AllowedScopes list for the client

      AllowedScopes = new List<string>
                  {
                      IdentityServerConstants.StandardScopes.OpenId,
                      IdentityServerConstants.StandardScopes.Profile,
                      IdentityServerConstants.StandardScopes.Email,
                      "roles",
      
                  },
      
    3. In the request add a request for the roles scope.

            "RequestedScopes": "openid profile email roles",