Which claims your applications need in Keycloak tokens
An application often needs a value in its token that Keycloak does not add by default, such as a department, a tenant ID, a business role or a specific audience. The default claims cover the basics of identity, but an application that routes data by tenant or checks a role before showing a screen needs that value present in the access token or ID token it receives. In Keycloak, the component that puts such a value into a token is a protocol mapper. A protocol mapper takes a value from a user, a role, a group or the session and writes it into a named claim in the token issued for a client.
Protocol mappers can be attached in two places. A mapper defined on a client scope applies to every client that uses that scope, which suits a claim shared by several applications, such as a tenant ID used across a product family. A mapper defined directly on a client applies only to that client, which suits a claim that only one application needs or a value that must not leak to others. The Keycloak server administration guide describes both locations under the client scope and client configuration sections. Before building anything, list each claim, the applications that read it, and whether any other client should receive it. That list decides where each mapper lives and avoids a claim that appears in tokens nobody should see.
Teams usually need a mapper when an application reads a value it cannot derive from the subject ID, or when a downstream service must check a value in the token rather than query another system. Each new claim also adds to the token size and to what every receiving application must handle, so confirm that each claim is needed, its name is stable and its source value is maintained by the right system. Confirm the exact mapper types and options available in your release against the server administration guide, since the list of built-in mappers can change between versions.
Built-in mapper types and when each fits
This table compares the built-in protocol mapper types for user attributes, roles, groups, audiences and session or client data. Read each row as a question: what does the application need in its token, and which mapper writes it. Confirm the exact mapper list and options in the Keycloak version you run, because the server administration guide describes them per release.
| Mapper type | What it writes into the token | Typical application need | Main configuration choices |
|---|---|---|---|
| User attribute | A single user attribute value, placed under a claim name you choose | Department, tenant ID or employee number that the app reads for authorization | Token claim name, multivalued handling, and whether it goes into the ID, access or userinfo token |
| User realm role | Realm-level roles assigned to the user | Coarse access decisions shared by several clients | Claim name, multivalued output, and which token types carry the claim |
| User client role | Roles scoped to a specific client, grouped under that client's name | Per-application permissions that should not leak to other applications | Client selection, claim name, and whether roles appear in the access token only |
| Group membership | The paths of groups the user belongs to | Team or organization membership for apps that route users by group | Full path or short name, claim name, and token types; group paths can change with directory sync |
| Audience | The aud claim, naming the APIs the token is intended for | Resource servers that reject tokens not addressed to them | Included client audience, and whether the audience comes from a client role or a fixed client |
| User session or client data | Session details such as the client ID or session state, or values tied to the client | Auditing, logging, or per-client context inside the application | Claim name and token types; confirm which fields your version exposes before relying on them |
How client scopes decide where claims appear
In Keycloak, a claim reaches a token only when a mapper runs for that client's token request. Where the mapper sits (on a client scope or directly on a client) and whether the scope is default or optional decide which clients receive it, so these choices should be made deliberately before any claim goes live.
Scope-level mappers reach every client
A mapper attached to a client scope runs for every client that uses that scope, including clients you add later. This is efficient for claims such as a department or tenant attribute, but it also means a new client inherits the claim without anyone reviewing it. Before attaching a mapper to a shared scope, list the clients that already use the scope and confirm each one should receive the value.
Client-level mappers stay with one client
A mapper defined directly on a client affects only that client's tokens. Use this placement for claims that a single application needs, such as an audience for one API or a role list for one back end. The trade-off is repetition: the same mapper copied across many clients is harder to change consistently, so review the duplicates whenever a claim name or source attribute changes.
Default scopes add claims automatically
Default client scopes are included in every token request for the client without the application asking for them. Typical examples are the profile and email scopes. A claim placed on a default scope therefore appears in tokens for all clients that keep that default, so check the default list on each client, not only on the scope itself.
Optional scopes add claims on request
Optional client scopes add their mappers only when the application requests the scope name in the authorization request. This is the safer choice for sensitive claims, since a client receives them only if it asks. Confirm that each consuming application actually sends the scope, because a missing scope produces a token without the claim and often no error.
Leaking claims to unintended clients
The main risk is a claim reaching a client that should not see it, through a default scope, a shared scope or a client that a team copied from another one. Personal data, internal group names and admin roles are the usual candidates. Review which clients use each scope, and restrict high-sensitivity claims to clients with a documented need.
Testing the effective token per client
Inspect the token each client actually receives, not the configuration screens. Use the client's Client scopes evaluate function in the admin console to see the mappers that would run, then request a token with a test user and decode it. Repeat this for each client after changing a scope, since one change can alter several applications at once.
Keycloak docsAdding a claim to a token step by step
This sequence takes one piece of user data, such as a department attribute, and carries it into an access or ID token for one client, then confirms the claim arrives where the application expects it. Each step ends with a check you can run before moving on.
Define the source data and claim name
Decide where the value comes from before touching any mapper. It can be a user attribute, a realm or client role, or group membership, and it must already exist in the realm or be set for a test user. Write down the claim name the application will read, the value format, and whether the claim should be a single value or a list. Who does this: the application owner and the identity administrator together. You know it is done when the source is visible on a test user's profile or role mappings in the admin console, and the claim name is agreed in writing.
Create or select a client scope
Open the client scopes area of the realm and either select an existing scope for the application or create a new one, for example one named after the application's data. Keep one scope per logical set of claims so that you can add or remove them later without editing every client. Set the scope's type and protocol to match the client, which is OpenID Connect for most web and API clients. Menu labels and layout differ between Keycloak versions, so confirm the path against the release you run. You know it is done when the scope appears in the realm's client scope list with the OpenID Connect protocol.
Add the protocol mapper with its claim name and token types
Inside the scope, add a mapper of the type that matches the source: a user attribute mapper, a role or group mapper, or an audience mapper for the aud claim. Set the token claim name to the agreed name, choose the claim JSON type, and turn on the token types the application needs, such as ID token, access token, or userinfo. Leave the other options at their defaults unless the application requires a change. Where the mapper form or option names differ in your version, follow the labels shown in your console and the server administration guide. You know it is done when the mapper is saved with the claim name and the token types you chose.
Assign the scope to the client as default or optional
Open the application's client and go to its client scopes tab. Add the new scope as a default scope if every token for this client should carry the claim, or as an optional scope if the application should request it explicitly with the scope parameter. Optional scopes are the safer starting point for claims that only some flows need, because they limit what each token contains. Confirm that the client is not sharing this scope with other clients unless that is intended. You know it is done when the scope is listed under the client's default or optional scopes with the correct assignment.
Request a token and decode it
Sign in as the test user using the client's normal flow, or request a token directly from the realm's token endpoint for a test client. If you requested an optional scope, include it in the scope parameter. Paste the access token or ID token into a JWT decoder used only with non-production data, or decode the payload locally. Check that the claim name, value, and JSON type match what you wrote down, and that the claim appears only in the token types you enabled. You know it is done when the decoded payload contains the expected claim with the expected value.
Confirm the claim with the userinfo endpoint
Call the userinfo endpoint with the access token as a bearer token. Compare the response with the decoded token. The claim should appear there if you enabled the userinfo token type, and it should be absent if you did not. This check catches mappers that work for tokens but not for userinfo, which matters when the application reads profile data from userinfo rather than the ID token. You know it is done when the userinfo response matches your expectations for that claim.
Test with a user who lacks the source data
Repeat the token request for a user who has no value for the attribute, or who does not hold the role or group. Decide with the application owner whether the claim should be omitted, empty, or cause a failure in the application, and confirm that the application handles that case. Then record the mapper settings, the scope name, and the client assignment in your configuration repository, so the same change can be repeated in other environments. You know it is done when the missing-data result matches the agreed behavior and the configuration is recorded.
When script mappers and custom mapper providers apply
Reach for a script mapper only after you have confirmed that the feature is in the release you run and that you accept its preview status. Script mappers let a client scope compute a claim value from user data in a short script, which can cover cases the built-in mappers do not, such as deriving a tenant label from an attribute. Because the feature is in preview, its behavior, enablement and configuration can change between releases, so confirm the status and any feature flag against the release notes for your exact version before you put it in a production token path. Check the current state of the feature in the server administration guide and in the upgrade notes for each minor release you plan to adopt, and record which version you tested.
A custom mapper provider is the other route. It is a Java SPI provider that you compile, package as a JAR and deploy into the Keycloak server, and it gives you full control over how claims are built. The cost is ownership: your team writes the code, keeps the build aligned with the Keycloak version, and retests token contents on every minor release. Before choosing this path, compare the requirement against the built-in mappers for attributes, roles, groups and audiences, which need no code and carry far less upgrade work. Read the SPI-related entries in the upgrade notes for each target release, because a change to the provider interface breaks the JAR until it is rebuilt.
The practical decision is therefore a trade-off. Built-in mappers are cheaper to maintain across upgrades and easier to review with a security team, while script mappers and custom providers add testing burden and version coupling. Ask a partner, or your own team, to estimate the testing effort for each candidate claim, including the regression tests that compare issued tokens before and after an upgrade. A quote should separate the initial build from the recurring work of rebuilding and retesting each time the server changes.
How a mapper adds a claim during token issuance
The flow starts when a client requests tokens from Keycloak's token endpoint with a set of scopes. Keycloak resolves the default and optional client scopes for that client, then runs each attached protocol mapper against the user and session data. The mapped values land in the ID token, the access token or the userinfo response, depending on each mapper's settings. The trust boundary sits between the client application and the token endpoint, so anything the client sends as a scope or parameter only changes which mappers run, never what a mapper reads. When a claim is missing, check the client scope assignment first, then the mapper's token type setting.
Scope resolution and mapper execution inside Keycloak during token issuance.
Security risks in custom token claims
Every claim a mapper adds becomes data that travels with the token to clients, APIs, logs and caches. The cards below cover the places where that data can leak, get accepted by the wrong service, or outlive the controls that were meant to govern it.
Claim exposure to third-party clients
A token is readable by the client that receives it, and access tokens can be inspected by anyone holding them. A mapper added to a client scope that a third-party or public client requests may expose internal group names, role structure or user attributes that the client never needed. Review each mapper's client scope assignment and confirm that only first-party clients that need a claim can request it. Ask whether any claim reveals more about the organization than the application needs.
Keycloak server admin docsSensitive attributes in logged tokens
Tokens are often written to application logs, debugging output, error traces or proxy access logs, and they may be cached by gateways and clients. A mapper that copies a national ID, health indicator or internal risk score into the token places that value in every one of those stores. Keep personal and regulated attributes out of tokens unless the consuming service has a documented need, and confirm that logging configurations redact bearer tokens.
Audience misconfiguration across APIs
An audience (aud) claim tells a resource server which API a token was issued for. If audience mappers are broad or missing, one API can accept a token that was meant for another service, which turns a single compromised client into access across several systems. Map each audience to exactly the resource servers that should trust it, and test that an API rejects tokens issued for a different audience.
Token lifetimes and signing keys
Claims stay valid until the token expires, so a role or group change may not reach an application until the next refresh. Long access token lifetimes widen the window in which a removed entitlement still works, and key material used to sign tokens must be rotated on a schedule your security policy sets. Review realm token lifetimes and key rotation whenever claim content changes, and confirm the lifetime values your organization has approved in writing.
Script mappers and custom providers
Script mappers run code on the server and are in preview, so their behavior and upgrade path are less settled than the built-in mappers. A custom mapper provider is Java code that must be rebuilt and retested against each Keycloak version you adopt. Both add review burden: confirm who can edit scripts in the admin console, keep them under source control, and plan a retest with every upgrade.
Keeping claim configuration stable across upgrades
Claim mappings are configuration, not code, so they must be treated as a managed asset that survives every Keycloak minor upgrade and database migration. Each protocol mapper, client scope assignment and default scope lives in the realm, and a change to any of them alters the tokens every relying application receives. Before you upgrade, export the realm configuration and keep it in version control so you can diff it against the state after the upgrade. The Keycloak upgrading guide lists the changes each release introduces, and you should read the section for every minor version between your current release and the target before you touch a cluster.
Keycloak plans four minor releases a year and says breaking changes in a minor release will be opt-in, so an upgrade should not silently change how your mappers behave. That policy shifts the risk to your change process: you still need to confirm that the defaults you rely on, such as which scopes are attached to a client, have not moved. Schema migration runs automatically at startup by default, while manual migration, which the upgrading guide suggests for large deployments, lets a DBA review the SQL first. Confirm with your platform team which of the two your environment uses and who approves the migration script.
Retest claims after each upgrade with a fixed set of checks: decode an access token and an ID token for each client, compare the claim names, types and values against a recorded baseline, and confirm that audience and role claims still reach the resource servers that depend on them. Keep these checks in a repeatable script and run them in a staging realm restored from a recent database backup before production. Record the exact Keycloak version, the realm export and the test results together so an auditor or incident responder can see what changed and when.
Limits to confirm in your environment
Protocol mapper behavior depends on the Keycloak version you run, the gateways and APIs that receive the tokens, and the applications that parse them. The cards below list the checks to make in a test realm before any claim design reaches production, and each check should be confirmed against the vendor documentation for your exact release.
Mapper types in your version
Confirm which built-in mapper types your Keycloak release provides for user attributes, realm and client roles, groups and audiences, and which ones need a custom provider. Mapper names and configuration options have changed between releases, so check the server administration guide for the version you run. Build each claim you need in a test realm and decode the resulting token to confirm its name, type and position.
Keycloak docsScript mapper availability
Script mappers are a preview feature, so confirm whether your release enables them by default, how your deployment turns them on, and whether your security policy allows executing scripts inside the identity provider. Ask who will review and maintain each script during upgrades. If the feature is not supported for your use, plan a custom mapper provider instead.
Token size limits at gateways
Every extra claim, group and audience adds bytes to the access and ID tokens. Check the maximum header size accepted by your reverse proxy, API gateway, load balancer and any service mesh in front of your APIs, since a large token can be rejected before the application sees it. Measure token size with realistic group memberships for your heaviest users, not only with a test account.
Downstream claim parsing
Confirm that each application and API reads custom claims with the names, types and multi-value formats you configured. A claim that changes from a string to an array, or a group path that gains a leading slash, can break authorization without any error at sign-in. Test each consuming service with tokens from a test realm and record the expected claim shape in your integration documentation.
Scope and token exposure
Confirm which client scopes add each claim to the access token, the ID token and the userinfo response, and whether a client can request a scope it should not hold. Review each claim for personal data, since tokens are often logged or forwarded. Record the owner of each scope so that a later change to a shared scope is reviewed before it reaches every client.
Questions teams ask before adding custom token claims
Are the built-in Keycloak protocol mappers enough for our application claims?
For most applications, yes. Keycloak's built-in mappers cover user attributes, realm and client roles, group membership and audience values, and client scopes control which of them reach each token. Custom claims are usually needed only when a value must be computed from several sources, reformatted for a downstream API, or derived from logic the built-in mappers cannot express. Before writing anything, list each claim your applications need, then check the mapper types in the server administration guide. Most teams find that a combination of user attributes, role mappers and an audience mapper covers the list. Confirm the exact mapper options against the Keycloak version you run, because option names and defaults can change between releases.
What does a custom mapper provider cost in effort and upgrade exposure?
A custom mapper provider is Java code that implements a Keycloak provider interface, packaged and deployed into the server. The one-time cost is design, development, unit and integration testing, and a code review by someone who knows Keycloak internals. The recurring cost is upgrade exposure: each Keycloak release can change the provider APIs, so the code must be rebuilt, retested and redeployed against every minor release you adopt. Keycloak says breaking changes in a minor release will be opt-in, which reduces surprises but does not remove the need to test. Ask any partner to quote the build, test and upgrade work separately, and to state which Keycloak versions the code will be verified against.
How long does a typical claim change take to test?
No fixed duration applies, because the time depends on the drivers below. Tests grow with the number of applications that consume the token, the number of client scopes and mappers that touch the claim, whether the claim feeds authorization decisions in downstream services, and how many identity sources supply the data. A change that only adds a static audience value is quick to verify. A claim that combines roles from a brokered identity provider with group data needs tests for each path, including users who arrive through different login methods. Ask for the test plan and the list of consuming applications in any quote, since those two items set the effort more than the mapper itself.
What does the work need from our team?
Your team needs to provide several inputs that outsiders cannot infer. These include the list of applications and APIs that read the token, the claim names and value formats each one expects, the user attributes and roles in the source directory or identity provider, and the test accounts that represent each user type. Someone must also approve which claims are sensitive, because extra claims enlarge what a leaked token reveals. A named owner should sign off on the client scope design and on the production change window. Without these inputs, the work tends to stall at discovery, so raise them in the scoping conversation.
Can our internal team add custom token claims without outside help?
Yes, if the team has Keycloak administration experience and someone who can write and test Java for a custom provider. Built-in mapper configuration needs no code and can be handled by an administrator who understands OpenID Connect scopes and token contents. Custom mapper providers require development skills, a build pipeline, and a test environment that matches production realms and clients. Teams without that combination often choose a partner for the first provider and then keep the maintenance in-house. Whichever route you take, document each claim, its source, and the Keycloak version it was verified on.
Which claims should we avoid putting into tokens?
Keep tokens small and limit them to data that relying parties need to make decisions. Personal data that a resource server can fetch from a directory is better left out of the access token, because tokens are often logged, cached or forwarded. Review each proposed claim against your data handling rules and your access control design before adding it. Keep in mind that a claim added to an access token reaches every application that accepts that token, so scope mappers to the clients that need them.
How do custom claims affect upgrades to newer Keycloak releases?
Built-in mapper configuration usually survives upgrades, but you should still re-test token contents after each minor release, since defaults and mapper behavior can change. Script mappers are in preview, so treat them as a higher upgrade risk than standard mappers and plan to re-verify them each time. Custom provider code carries the highest exposure because it depends on internal interfaces. Read the upgrading guide and the release notes before each change, and keep a regression suite that decodes tokens and checks the claims for each client.
How DeployOpen scopes claim work
Claim work starts with an inventory, not a mapper. Before any configuration changes, DeployOpen lists every client that receives tokens, the claims each application actually reads (for example, a user's email, a tenant identifier, a role an API checks, or an aud value a resource server validates), and the source each claim comes from: a user attribute, a realm or client role, a group, or a value computed by a custom provider. The inventory also records which tokens carry each claim (ID token, access token, userinfo response) and which resource servers consume it. That list becomes the written scope, and any claim without a named consumer is questioned before it is built.
Next, DeployOpen designs the client scopes and mappers that produce those claims. Shared claims go into client scopes so they can be attached to several clients and kept out of the ones that do not need them. Each mapper is set to the token types and scopes it belongs to, and the design notes state which mapper type is used and why: attribute, role, group or audience mapping. Script mappers are treated with caution because they are in preview and their long-term support should be confirmed against the release in use. Where no built-in mapper fits, the work is scoped as a custom mapper provider with its own build, test and upgrade plan. Each choice is recorded so an administrator can see what a claim means and where it comes from.
Testing and documentation close the scope. DeployOpen decodes real tokens from each client and flow, checks that claims appear where the design says and nowhere else, and confirms that resource servers accept the audience and roles they receive. The configuration is exported and documented so changes can be reviewed and replayed after a Keycloak upgrade. Engagements are fixed-scope, with deliverables and timelines agreed in writing before work starts, and a quote follows from that written scope. Ongoing retainers cover upgrade checks and retesting when new clients or claims are added. Ask any partner for the claim inventory and the test evidence as deliverables, not only the configured realm.

