Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 37 ยท Customization

Protocol Mappers and Custom Claims

Add custom claims to Keycloak tokens: client scopes, protocol mapper types, user attribute and role mappers, audience claims, nested claim names, and where each claim lands.

An access token is only useful if it carries the facts your API needs: who the user is, which roles they hold, which tenant they belong to, which audience the token is for. Keycloak builds tokens from the user and session using protocol mappers. Each mapper takes one piece of data (an attribute, a role list, a fixed value) and writes it into a claim of the access token, the ID token, the UserInfo response, or any combination.

Keycloak does not run on this site. The admin console steps describe a recent version, and the TryIt blocks are JavaScript stand-ins that model a mapper pipeline so you can see how claim names and targets behave.

Where mappers live

Mappers belong either to a client (dedicated scope) or to a client scope that many clients share:

  • Clients > your client > Client scopes > <client>-dedicated: mappers used only by this client.
  • Client scopes: reusable bundles. Assigning a scope to a client as Default includes its mappers in every token; Optional includes them only when the request asks for that scope with scope=....

Reusing client scopes keeps token shape consistent across apps and makes changes one-place edits. Built-in scopes such as profile, email, roles, and web-origins are made of mappers too.

Common mapper types

Mapper Typical use
User Attribute Copy a user attribute (for example department) to a claim
User Realm Role List realm roles in a claim
User Client Role List roles of a client in a claim
Group Membership List group paths in a claim
Audience Add a client or custom value to aud
Hardcoded claim Fixed value for every token (for example environment)
User Session Note Claim from session data
Script Run JavaScript: deprecated and disabled by default; avoid

Every mapper has settings that matter:

  • Token Claim Name: the claim key. A dot creates nesting: org.tenant.id produces { "org": { "tenant": { "id": ... } } }. Escape a literal dot with a backslash.
  • Claim JSON Type: String, long, int, boolean, or JSON, so the value arrives with the right type.
  • Add to ID token, Add to access token, Add to userinfo, Add to token introspection: where the claim appears.
  • Multivalued: array or single value.

A mapper pipeline in code

Run the pipeline in your head, or in this stand-in:

JS Stand-in: mapper pipeline with nested claim names

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

No output.

The three outputs differ only because each mapper ticks different targets. That is the main knob: keep the ID token small (it goes to the browser and is often stored), and put API-specific claims on the access token.

Roles in tokens

By default Keycloak adds realm roles under realm_access.roles and client roles under resource_access.<client>.roles, through the roles client scope. Many libraries expect a flat roles or groups claim instead. Add a User Realm Role mapper with Token Claim Name roles to produce a flat array. A User Client Role mapper accepts a Client ID so you only include that client's roles, which keeps tokens smaller.

The audience claim

An API should accept only tokens meant for it. By default the access token's aud may not contain your API's client ID. Fix it with the Audience mapper (set Included Client Audience to the API's client ID), or by enabling Audience Resolve, which adds the clients whose roles appear in the token. The JWT verifier project checks aud as a mandatory step.

Check what you issue

Each mapper makes tokens larger. Larger tokens slow every request and can exceed header limits (often 8 KB at proxies). Watch for:

  • Group or role lists with hundreds of entries: use filters ("Full group path" off, role prefix filters) or fetch lazily from UserInfo.
  • Duplicate claims from overlapping scopes.
  • Personal data in ID tokens that are stored in browsers.

Use Clients > Client scopes > Evaluate in the admin console: choose a user and see the generated access token, ID token, and UserInfo without writing any app code. It is the fastest way to debug a missing claim.

Estimating token size

Tokens are base64 text, so their size is roughly 4/3 of the JSON size, plus the header and signature. A small estimator helps judge a design:

JS Stand-in: estimate encoded token size

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

No output.

Security notes

  • Never put secrets or password hashes into claims.
  • Do not trust claims for authorization unless the token signature has been verified by your API.
  • User-editable attributes should not be mapped into authorization claims unless users cannot set them (use user profile permissions to prevent self-editing; see user profile).
  • Remember token lifetimes: a claim stays valid until the token expires, even if you change a role right now.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the Token Claim Name org.tenant.id create?

    Dots create nesting unless escaped with a backslash.
  2. 2. Where should API-specific claims normally go?

    The access token is what the API receives; keep the ID token lean.
  3. 3. How do you make an API accept only tokens meant for it?

    An Audience mapper puts the API's client ID into aud, and the API must check that claim.
  4. 4. Which admin console tool shows the tokens a user would receive?

    Evaluate generates example tokens for a chosen user and scope selection.

Summary

  • Protocol mappers write claims into access tokens, ID tokens, UserInfo, and introspection.
  • Client scopes bundle mappers; Default scopes are always applied, Optional ones on request.
  • Dots in claim names create nesting; JSON type controls value type.
  • Use the Audience mapper and verify aud.
  • Keep tokens small and free of secrets, and test with Evaluate.

Next: User Profile and Required Actions