Search code examples
openid-connectidentityserver4

Roles not in Token via IdentityServer4


I'm using IdentityServer4 to authenticate my internal app. I have a service that I'm calling inside of my GrantValidator that validates the user name and password. That service returns a list of roles for the user

    public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
    {


        var loginResponse = await loginService.ValidateCreds(context.UserName, context.Password)

        if (loginResponse.Success)
        {
            var roleClaims = loginResponse.Roles?.Select(x => new Claim(ClaimTypes.Role, x)) ?? Enumerable.Empty<Claim>();
            // The claims argument doesn't seem to do anything!
            context.Result = new GrantValidationResult(loginResponse.UserId, "password", roleClaims);
        }
        else
            context.Result = new GrantValidationResult(TokenRequestErrors.InvalidClient, "Invalid Credentials");
    }

The returned token:

{
  "nbf": 1491409664,
  "exp": 1491413264,
  "iss": "http://localhost:5000",
  "aud": [
    "http://localhost:5000/resources",
    "redacted"
  ],
  "client_id": "localhost",
  "sub": "nouser_222222222|1234567",
  "auth_time": 1491409634,
  "idp": "local",
  "clientid": "dfc962d7-c731-4d42-b0c8-bec766dc7813",
  "scope": [
    "profile",
    "redacted"
  ],
  "amr": [
    "password"
  ]
}

Solution

  • The profile service is responsible for putting claims into a token. Implement IProfileService and register it in DI.

    In there you have access to the claims that the resource owner validator put into the subject and can then emit them by putting them on the IssuedClaims collection.