Claim Customization via Protocol Mappers in Keycloak

Claim Customization via Protocol Mappers in Keycloak

A beginner-friendly, complete guide to how Keycloak decides exactly what information gets stamped into a token — and how you can reshape that information without touching a single line of application code.

Picture a company badge printer at the front desk of a large office building. Every visitor gets a badge, but not every badge looks the same. A contractor’s badge might print their name and “Contractor — Escort Required” in red letters. A full-time employee’s badge prints their name, department, and a photo. A visiting executive’s badge might additionally print “All-Floor Access.” The printer is not guessing — someone configured rules ahead of time that say, for each type of visitor, exactly which fields get pulled from the visitor database and printed onto the badge, and in what format. In Keycloak, tokens are the badges, and protocol mappers are those printing rules. They decide which pieces of a user’s or client’s information — called claims — get written into a token, how they are named, and how they are shaped, before that token is ever handed to an application. This tutorial explains claims and protocol mappers from first principles, then walks through the architecture, the internal mechanics, the trade-offs, the security implications, and the patterns that separate a clean Keycloak setup from a fragile one.

1What Are Claims?

Before customizing anything, it helps to be precise about what is actually being customized.

A claim is simply a labeled piece of information about a user or a client, packed inside a token. If an access token or an ID token is like a small identity document, then each claim is one line printed on that document — a name, an email address, a role, a department, an account tier, or anything else worth stating.

Keycloak, like any OpenID Connect-compliant identity server, issues tokens containing a set of standard claims by default — things like the subject identifier, the token’s expiry time, and the issuer’s address. But real applications almost always need more than the defaults. A shopping application might want a “loyalty tier” claim. An internal admin tool might want a “department” claim. A partner-facing API might want a claim confirming which specific product the user is licensed to use.

Simple Analogy

Think of a claim like a single field on a shipping label. “Destination Address,” “Weight,” and “Fragile: Yes” are all separate claims about the same package. A shipping company does not print every fact it knows about a package — only the fields relevant to getting it delivered correctly. Claims work the same way: only the facts an application actually needs get printed onto its tokens.

i
Where This Fits

Keycloak stores rich information about every user — attributes, group memberships, assigned roles — in its internal database. Claims are the bridge between that internal database and the outside world: they decide what subset of that information actually leaves Keycloak inside a token.

2What Is a Protocol Mapper?

If claims are the printed lines, a protocol mapper is the rule that decides what gets printed and how.

A protocol mapper is a configured rule inside Keycloak that transforms a piece of user, client, or session data into a claim on a token. The word “protocol” refers to the fact that these mappers apply to specific token protocols — most commonly OpenID Connect, but Keycloak also supports mapping for the older SAML protocol used by many legacy enterprise systems.

Each protocol mapper answers three questions: where does the data come from (a user attribute, a group name, a role, a hardcoded value, or a piece of session information), what should the resulting claim be named, and which tokens should carry it — the access token, the ID token, or both.

Source

User Attribute Mapper

Pulls a custom field stored on the user’s profile — such as “employeeId” or “department” — and places it into a token under a chosen claim name.

Source

Group Membership Mapper

Adds a claim listing the groups a user belongs to, which many applications use to drive coarse-grained access control.

Source

Role Mapper

Adds a claim listing the realm-level or client-level roles assigned to the user, often the primary signal an application uses for authorization decisions.

Source

Hardcoded Claim Mapper

Adds a fixed, unchanging value to every token issued for a particular client — useful for signaling which application or environment issued the token.

!
Common Misconception

Beginners sometimes assume claims are automatically generated from “whatever is in the database.” In reality, nothing appears in a token unless a protocol mapper explicitly says it should. Without a mapper, even rich, detailed user data sits invisibly inside Keycloak and never reaches the application.

3Where Mappers Fit in Keycloak’s Architecture

Protocol mappers do not float in isolation — they are attached to specific places inside Keycloak’s structure.

Mappers can be attached in two different places, and the difference matters a great deal for how a system scales.

Client-Level Mapper

Attached to One Application

Configured directly on a single registered client. Only tokens issued for that specific application receive this claim. Useful for claims that only make sense to one system.

Client Scope Mapper

Attached to a Reusable Scope

Configured on a named “client scope” that can then be shared across many clients. Changing the mapper once updates the claim behavior everywhere that scope is used.

Client scopes are, in effect, reusable bundles of protocol mappers and permissions. Rather than configuring the same “department” claim mapper individually on fifteen different applications, an administrator defines it once inside a shared client scope called, say, “employee-profile,” and then simply attaches that scope to every client that needs it. This is one of the most important architectural decisions in a growing Keycloak deployment, because it turns fifteen places to maintain into one.

Default vs Optional Client Scopes

Keycloak further distinguishes “default” scopes, which are automatically included in every token issued to a client, from “optional” scopes, which only apply when explicitly requested during login — giving fine control over when certain claims are included at all.

2
Levels a mapper can be attached at
1
Shared scope can serve many clients
2
Token types a mapper can target — ID and access

4Types of Protocol Mappers in Depth

Keycloak ships with a well-stocked library of built-in mapper types, and understanding the full menu prevents reinventing the wheel.

Mapper TypeTypical UseData Source
User AttributeCustom profile fields like job title or regionUser profile attributes
User PropertyBuilt-in fields like email or first nameCore user record
Group MembershipCoarse access grouping, e.g. “finance-team”Group assignments
Realm Role / Client RoleFine-grained permission signalingAssigned roles
Hardcoded ClaimConstant values like an environment tagStatic configuration
Script-Based MapperCustom transformation logic beyond simple field copyingCustom evaluation logic
Audience MapperDeclaring which service the token is intended forClient configuration

Most day-to-day claim customization needs are satisfied by the first four categories in that table — they require no custom logic, only configuration. The script-based mapper exists for the rarer cases where a claim needs to be computed rather than simply copied, such as combining two attributes into one formatted string, though many Keycloak deployments disable script mappers entirely for security reasons, which is discussed later in this tutorial.

i
The Audience Claim Deserves Special Attention

The audience (“aud”) claim tells a resource server that a token was actually intended for it, and not accidentally reused against a different, unrelated service. Configuring this correctly is one of the more important, and most frequently overlooked, mapper responsibilities.

5Internal Working: How Mappers Transform a Token

Understanding the internal sequence demystifies what actually happens between “user logs in” and “token contains a claim.”

Every time Keycloak is about to issue a token — whether at initial login, a token refresh, or a token exchange — it runs through the same internal choreography before handing anything back to the requesting application.

1

Authentication completes

The user successfully proves their identity, and Keycloak establishes a session tied to that user and the requesting client.

2

Keycloak gathers the client’s assigned scopes

It resolves the full list of default and requested optional client scopes attached to that specific client.

3

Every mapper attached to those scopes is evaluated

Each protocol mapper runs in turn, reading its configured data source — an attribute, a role, a group, or a hardcoded value.

4

Resulting claims are written into the token structure

Each mapper’s output is inserted under its configured claim name, into the access token, ID token, or both, exactly as configured.

5

The token is signed and finalized

Once every applicable mapper has contributed its claim, Keycloak cryptographically signs the completed token so any tampering afterward can be detected.

Simple Analogy

This is much like an assembly line stamping a passport. One station stamps the name, another stamps the date of birth, another stamps the issuing country, and a final station applies the security seal. Each station only knows how to stamp its own field — the protocol mapper is that station — and the seal at the end (the token signature) guarantees nobody can quietly add or alter a stamp afterward.

6The Full Token Issuance Lifecycle

Here is the entire journey visualized, from a user’s login attempt to an application reading a customized claim.

sequenceDiagram
    participant U as User
    participant K as Keycloak
    participant CS as Client Scope
    participant PM as Protocol Mappers
    participant A as Application
    U->>K: Logs in
    K->>CS: Resolves default + requested scopes
    CS->>PM: Triggers each attached mapper
    PM->>PM: Reads attribute, role, group, or static value
    PM-->>K: Returns claim name and value
    K->>K: Assembles and signs the token
    K-->>A: Delivers token containing custom claims
    A->>A: Reads claims to drive its own logic
        
FIG 1 — How configured mappers turn user data into finished, signed claims inside a token

What makes this architecture powerful is that the application on the receiving end never needs to know how a claim was produced — whether it came straight from a database field, was computed by a script, or was simply hardcoded. It only needs to know the claim’s name and trust that Keycloak populated it correctly. This is the same separation of concerns seen in token introspection: the consuming application stays simple, while Keycloak absorbs the complexity.

“A claim is only as trustworthy as the mapper that produced it, and only as visible as the scope that carries it.”

7Advantages and Trade-offs

Claim customization is powerful, but like any flexible system, it comes with genuine costs to weigh.

Advantages

  • Applications receive exactly the data they need, shaped exactly how they need it, with no code-side transformation
  • Changes to claim behavior happen centrally in Keycloak, without redeploying applications
  • Reusable client scopes prevent duplicated configuration across many applications
  • Fine-grained control over which claims appear in which token type protects sensitive data from unnecessary exposure

Disadvantages / Trade-offs

  • Overusing custom claims can bloat token size, increasing bandwidth and parsing cost on every request
  • Complex mapper configurations become hard to audit as the number of clients and scopes grows
  • Script-based mappers introduce a maintenance and security burden beyond simple declarative configuration
  • Misconfigured scopes can accidentally leak sensitive attributes into tokens seen by client-side code
i
A Practical Rule of Thumb

Treat every claim as a small, permanent public commitment. Once an application starts depending on a claim’s name and shape, changing or removing it later requires coordinated updates everywhere that claim is consumed — so it pays to design claim names and structures carefully from the start.

8Security Considerations

Because claims travel inside tokens that are often decoded and inspected by client-side code, careless mapping can quietly leak information.

Access tokens are not always secret from the browser

In many single-page application flows, the access token or ID token is readable directly in the browser. Any claim mapped into that token — a salary figure, an internal ID, a private note field — becomes visible to anyone who opens their browser’s developer tools. Sensitive attributes should never be mapped into tokens destined for public, browser-facing clients.

Over-broad group and role claims

Including a user’s complete list of every group or role they belong to, across an entire organization, can unintentionally reveal internal organizational structure or unrelated project names to an application that had no legitimate need to know them.

!
Common Mistake

Attaching a broad, all-purpose “everything about the user” client scope as a default scope on every client, simply because it is convenient during initial development, and then never revisiting it before production launch.

Script-based mappers as an attack surface

Because script mappers can execute custom logic, an organization that allows untrusted or loosely-reviewed administrators to write them opens a path for malicious or careless logic to be embedded directly into the token issuance process. Many security-conscious deployments disable this feature entirely at the realm level.

Principle of Least Claims

A useful mental model borrowed from the broader security principle of least privilege: include the smallest set of claims that fully satisfies an application’s actual, documented need — nothing extra “just in case it’s useful later.”

9Monitoring, Logging, and Metrics

Claim configuration tends to be invisible until something goes wrong, so proactive visibility matters.

Token Size

Average Token Payload Size

Tracking how token size trends over time helps catch claim sprawl early, before it starts affecting network performance across every protected request.

Configuration Drift

Mapper and Scope Change Auditing

Keeping an audit trail of who changed which mapper and when helps trace down the source of an unexpected claim appearing — or disappearing — in production tokens.

Consumer Errors

Application-Side Claim Parsing Failures

Applications that suddenly fail to find an expected claim often indicate a scope was unintentionally detached from a client, or a mapper’s claim name was changed without downstream coordination.

Because claim customization is a configuration-driven feature rather than code, standard code-review discipline does not automatically apply to it unless an organization deliberately extends its change-management process to cover Keycloak realm configuration as well — typically by treating realm exports as version-controlled artifacts subject to review, just like application code.

10Design Patterns and Anti-Patterns

A handful of recurring patterns separate maintainable claim strategies from tangled, brittle ones.

Pattern: Purpose-built client scopes

Rather than one giant scope containing every possible claim, mature deployments define several narrow, purpose-built scopes — such as “billing-profile,” “support-context,” or “admin-flags” — and attach only the ones each client genuinely needs.

Pattern: Naming claims consistently

Establishing an organization-wide naming convention for custom claims, such as always prefixing internal claims with a namespace, prevents collisions with standard OpenID Connect claims and with claims introduced by other teams.

ANTI-PATTERN-01 Avoid
Problem

A single, sprawling default client scope accumulates every claim ever requested by any team over the years, and gets attached to every new client by default because “that’s what we’ve always done.”

Why It’s Harmful

New applications silently inherit access to sensitive claims they never asked for and may not even know exist, and removing anything from the scope later risks breaking unrelated applications quietly depending on it.

Correct Approach

Break the sprawling scope into smaller, purpose-specific scopes, and require each client to explicitly opt into only the scopes it actually needs.

ANTI-PATTERN-02 Avoid
Problem

Business logic that decides authorization outcomes gets embedded directly inside a script-based protocol mapper, rather than inside the application itself.

Why It’s Harmful

This scatters critical decision logic away from version-controlled application code and into a configuration layer that is harder to test, review, and roll back safely.

Correct Approach

Use mappers only to surface raw facts as claims — roles, attributes, group names — and let the consuming application decide what those facts mean for authorization.

11Best Practices and Common Mistakes

A practical checklist for teams setting up or auditing claim customization.

1

Map only what is genuinely needed

Every additional claim is a small, permanent increase in token size and a small increase in what a client can see about a user.

2

Keep sensitive claims out of browser-visible tokens

Reserve highly sensitive attributes for server-to-server contexts, such as introspection responses, rather than tokens read directly by front-end code.

3

Prefer configuration over scripting

Use built-in mapper types whenever possible, and reserve script-based mappers for genuinely irreplaceable custom logic, subject to strict review.

4

Document every custom claim

Maintain a shared, discoverable record of what each custom claim means, where its data comes from, and which applications depend on it.

5

Treat scope and mapper changes as reviewable changes

Bring the same review discipline applied to application code to realm configuration changes affecting claims.

!
Frequently Seen Mistake

Assuming a claim removed from a mapper today has no effect on production, without checking whether any application has silently come to depend on its presence — a classic case of configuration drift causing an outage that looks, at first glance, like an application bug.

12Real-World and Industry Examples

Claim customization quietly powers a great deal of everyday enterprise software behavior.

Multi-Tenant Software-as-a-Service Platforms

Vendors serving many corporate customers often map a “tenant ID” or “organization ID” claim into every token, letting a single shared application instance correctly isolate one customer’s data from another’s without any extra lookup.

Enterprise Resource Planning Systems

Large internal business systems frequently map department, cost-center, and approval-level claims directly from Keycloak, letting workflow engines make routing decisions — such as who approves an expense report — purely from token contents.

Partner and Reseller Integrations

Companies exposing APIs to external partners often map a “partner tier” or “contract type” claim, allowing a single API gateway to apply different rate limits or feature access per partner without a separate lookup service.

Healthcare Access Systems

Systems governing access to patient records sometimes map a clinician’s department and role directly into tokens, so downstream systems can enforce “need to know” restrictions consistently across many independently built applications.

13Frequently Asked Questions

Q1Do protocol mappers only apply to OpenID Connect tokens?

No. While OpenID Connect claim mapping is the most common use case discussed in this tutorial, Keycloak also supports protocol mappers for SAML, allowing similar attribute customization for organizations still relying on that older protocol.

Q2Can the same claim appear in both the access token and the ID token?

Yes. Each mapper can be individually configured to add its claim to the access token, the ID token, or both, giving fine control over where each piece of information appears.

Q3What happens if two mappers try to produce a claim with the same name?

This can lead to one value overwriting the other in an order that is not always obvious, which is exactly why consistent claim naming conventions and careful scope design matter, as covered in the design patterns chapter.

Q4Are custom claims visible to anyone who has the token?

Any claim placed inside a JWT that reaches a browser or a mobile client can generally be decoded and read by that client, even without any special tools, so sensitive claims should be reserved for tokens that stay strictly server-side.

Q5Do claims automatically update if a user’s underlying attribute changes?

A claim reflects the underlying data at the moment a token is issued or refreshed — it is not continuously live. If a user’s attribute changes mid-session, existing tokens keep the old value until the next token issuance picks up the update.

Q6Is it possible to remove a default claim that Keycloak includes automatically?

Standard, protocol-required claims generally cannot be removed without breaking compliance with the underlying specification, but claims introduced through optional default scopes can usually be detached if they are not needed.

14Summary and Key Takeaways

Protocol mappers are the quiet, configuration-driven machinery that decides exactly what a token says about a user or a client, turning raw internal data into carefully shaped, purposeful claims. Used well — through narrow, purpose-built client scopes, disciplined naming, and a “least claims” mindset — they let applications receive precisely the information they need without writing custom transformation code, and let an entire organization change that information centrally as needs evolve. Used carelessly, they can bloat tokens, leak sensitive data to the wrong audiences, and create hidden dependencies that are painful to unwind later. The difference between the two outcomes almost always comes down to deliberate design rather than default configuration.

Key Takeaways

  • Claims are labeled facts inside a token — nothing appears there automatically without an explicit mapper.
  • Protocol mappers are the rules that decide a claim’s source, name, and destination token type.
  • Client scopes make mappers reusable — configure once, attach to many applications.
  • Every claim has a cost — larger tokens, more surface area for accidental data exposure.
  • Sensitive data belongs in server-side flows, not in tokens readable directly by a browser.
  • Script-based mappers are powerful but risky — prefer declarative configuration wherever possible.
  • Treat claim design as a long-term contract with every application that will come to depend on it.