Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 37 ยท OAuth2 and OIDC Flows

Client Scopes and Protocol Mappers: Shaping Keycloak Tokens

Control what goes into Keycloak tokens with client scopes and protocol mappers: default and optional scopes, built-in mappers, audience, hardcoded claims and full scope.

By default, Keycloak tokens contain a sensible set of claims. Real applications need more (a tenant ID, a department, an audience for one API) or less (no phone number, no unrelated roles). The tools for that are client scopes and protocol mappers. Understanding them lets you design tokens deliberately instead of by trial and error.

Client scopes

A client scope is a named, reusable package of mappers and role-scope settings. In the OAuth scope parameter a client names the scopes it wants (scope=openid email invoices:read). Keycloak includes each requested scope that is allowed for that client.

Each client lists its scopes on Clients > (client) > Client scopes with an assigned type:

  • Default: always applied, whether or not the request names it.
  • Optional: applied only when the request includes the scope name.

The realm-wide list lives under Client scopes; new clients get the realm's default set automatically (look at Client scopes > Type for Default, Optional or None).

Built-in scopes you will see:

Scope Adds
openid (implicit) Turns the request into OIDC
profile preferred_username, given_name, family_name, name, ...
email email, email_verified
roles realm_access, resource_access, and an audience from client roles
web-origins allowed-origins for CORS
basic sub and auth_time
acr The authentication context class reference
address, phone Address and phone claims (optional)
offline_access Allows an offline refresh token (optional)
microprofile-jwt, organization, service_account Special purpose scopes, depending on version and features

Each client also has a dedicated scope named {client-id}-dedicated, holding mappers and role-scope rules that apply only to that client. Put one-off claims there; put shared claims in a reusable scope.

Protocol mappers

A protocol mapper copies data to or from a token. Inside a scope, Add mapper > By configuration offers the types:

Mapper type Does
User Attribute Puts a user attribute into a claim
User Property Puts a built-in property (username, email, ...) into a claim
User Realm Role / User Client Role Puts roles into a claim, with a custom claim name
Group Membership Adds groups
Hardcoded claim A fixed value for every token
Hardcoded role Adds a fixed role
Audience Adds a client ID to aud
Audience Resolve Adds aud entries for every client the user has roles in
Script / Javascript Custom logic (disabled in new versions; use a Java mapper SPI instead)
User Session Note, Claims parameter, Allowed Web Origins Specialized

Common settings of a mapper: Name, Token Claim Name (dots create nested objects: a.b becomes { "a": { "b": ... } }), Claim JSON Type (String, long, int, boolean, JSON), Multivalued, and three switches: Add to ID token, Add to access token, Add to userinfo (and, in recent versions, token introspection).

Example: send the tenant ID to your API as tenant_id.

  1. Clients > invoice-web > Client scopes > invoice-web-dedicated > Add mapper > By configuration > User Attribute.
  2. Name tenant-id, User Attribute tenantId, Token Claim Name tenant_id, Claim JSON Type String, Add to access token on.
  3. Test with Client scopes > Evaluate: pick a user and generate an example access token to see the result without logging in.

Evaluate: your best debugging tool

On the client's Client scopes tab, the Evaluate sub-tab lets you choose a user and a scope string and then shows the generated access token, ID token and userinfo. Use it after every mapper change. It prevents shipping tokens with a missing claim or one claim too many.

Audience and why the API cares

The aud claim tells an API "this token is for you". Out of the box, an access token for demo-web usually has aud: account only. If your API is a separate client (invoice-api) you must make its client ID appear in aud:

  • Audience mapper: Included Client Audience = invoice-api. Simple and explicit.
  • Audience Resolve (in the roles scope): adds the audience automatically when the user has client roles of invoice-api in the token. Works because roles imply a relationship.

An API that rejects tokens with the wrong audience is correct; the fix is in Keycloak's mapper, not in the API.

Full scope allowed and role scope

Roles enter a token only if the client's Scope allows them. In Client scopes > dedicated scope > Scope tab:

  • Full scope allowed On: all the user's roles can appear (convenient, over-broad).
  • Off: only roles you list explicitly (and roles in scopes' role scope mappings) can appear. This is the least-privilege setting.

A request for scope=invoices:read does not grant the permission by itself. Scope requests are checked against what the client is allowed and what the user has. The API must still check the claim.

If a client has Consent required on, users see a screen listing the requested scopes (client scope's Display on consent screen and Consent screen text). Consent suits third-party clients you do not own. For your own first-party apps leave it off to avoid constant prompts.

Token claims in code (stand-in)

This runnable stand-in implements default and optional scopes, mappers with Add to access token style switches, nested claim names and audience, in about 50 lines. It is a model of the logic, not Keycloak.

Node.js Stand-in: scopes and mappers build a token

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Check the second line: aud is ["invoice-api"] because the user holds a client role there, and the API can now accept the token.

A claims linter (stand-in)

A second stand-in tests a decoded token against rules you would configure in your API, catching the typical mapper mistakes before production.

Node.js Stand-in: lint a token's claims

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Design rules

  1. Keep access tokens small and relevant to one API.
  2. Put identity and display data in the ID token or userinfo, not in access tokens.
  3. Put shared mappers in reusable scopes; one-off ones in the dedicated scope.
  4. Prefer optional scopes for sensitive data (phone, address) so clients must ask.
  5. Always test with Evaluate after changes, and remember that existing tokens keep their old claims until they expire.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the difference between a default and an optional client scope?

    Default scopes apply to every token request of the client; optional ones are applied only when requested.
  2. 2. Your API rejects tokens because aud lacks its client ID. What should you add in Keycloak?

    The audience claim is produced by an Audience or Audience Resolve mapper.
  3. 3. Which Keycloak tool shows the token a user would receive without logging in?

    Evaluate generates example access and ID tokens and userinfo for a chosen user and scope list.
  4. 4. What does turning off Full scope allowed do?

    Only roles in the client's role scope mappings can be included, which supports least privilege.

Summary

  • Client scopes bundle mappers; default scopes always apply, optional ones only when requested.
  • Protocol mappers copy attributes, roles, groups and fixed values into ID, access or userinfo tokens.
  • Use Audience or Audience Resolve so APIs see their client ID in aud.
  • Turn off Full scope allowed and keep tokens small; use Evaluate to check results.
  • Existing tokens keep old claims until expiry, so change and test before rollout.

Next: Identity Brokering Explained