Configure Realm Roles and the Role Claim

Configure Keycloak to include an end user’s realm roles in a top-level array claim that the database can map to data roles.

  1. Create realm roles, such as EMPLOYEE and MANAGER, and assign them to the required end users.

  2. Select the Keycloak client used for the browser application’s end-user sign-in. Add a User Realm Role protocol mapper to that client’s dedicated client scope.

  3. Configure the User Realm Role protocol mapper to include realm roles in a top-level array claim in the access token:

    • Set Token Claim Name to roles. Do not specify a nested path, such as realm_access.roles.
    • Enable Multivalued.
    • Enable Add to access token.

    If you use another claim name, specify that name in roles_claim in the database configuration.

  4. Preview the access token in the Keycloak Admin Console. Click Clients and select the client used for the browser application’s end-user sign-in. Click Client scopes, and then click Evaluate. Select the end user and any optional client scopes used during sign-in. Verify that the generated access token contains the expected realm roles in a top-level array. For example:

    "roles": ["EMPLOYEE"]

    See Evaluating Client Scopes in the Keycloak Server Administration Guide.

  5. Sign in as the end user and obtain an end-user access token. Inspect the token claims and verify that the top-level claim specified by roles_claim contains the expected realm roles. The token can also contain nested role claims. The database reads role values only from the configured top-level array claim.

See Realm roles, Role mappings in the token and Protocol mappers in the Keycloak Server Administration Guide.

Note: