Protocol Mappers in Keycloak: The Complete Guide
How Keycloak decides exactly what goes inside every login token — and how you can control it, chapter by chapter, from the ground up.
Imagine a passport office. Every citizen who applies gets a passport, but not every passport looks the same. A diplomat’s passport has extra stamps and privileges printed on it. A regular traveler’s passport has just the basics. Someone deciding to add their frequent-flyer number to the passport can do that too, if the office allows it. Keycloak is like that passport office, and every time someone logs in, it issues a “passport” — called a token. A Protocol Mapper is the rule that tells the office exactly what to print on that passport, for that person, in that situation. This guide walks through what Protocol Mappers are, how they work under the hood, how to use them well, and how to avoid the mistakes that trip up most teams the first time they touch one.
1What Is a Protocol Mapper?
Before diving into configuration screens, it helps to understand the problem Protocol Mappers were built to solve.
Keycloak in one paragraph
Keycloak is an open-source system that handles logins for other applications. Instead of every app writing its own username-and-password screen, checking passwords, and managing “forgot password” emails, apps hand that job to Keycloak. When someone logs in successfully, Keycloak doesn’t just say “yes, this person is real” — it hands the application a small digital document called a token. That token is what the application actually uses to know who the user is and what they’re allowed to do.
So what is a Protocol Mapper?
A Protocol Mapper is a small, named rule inside Keycloak that says: “take this piece of information about the user (or about the login itself) and put it into the token, under this name, in this format.” Without any mappers at all, a token would only carry the bare minimum — things like who issued it and who it belongs to. Protocol Mappers are how you enrich that token with everything else an application might need: a person’s full name, their email, their department, their roles, or even a completely made-up value that never changes.
Think of a token as a name badge handed out at a conference. By default the badge only has a random ID number on it. A Protocol Mapper is like a rule at the badge-printing desk: “also print the person’s job title,” or “also print which sessions they’re allowed into.” Each rule is independent — you can add as many printing rules as you like, and each one decides exactly one thing that appears on the badge.
Applications rarely trust a token blindly for every decision — but they do read fields out of it to personalize screens, enforce simple checks, and avoid extra network calls back to Keycloak. The richer and more accurate the token, the less an application has to ask elsewhere.
What problem existed before mappers?
Early identity systems either sent back everything about a user (wasteful and risky) or sent back nothing useful (forcing every app to make follow-up calls just to learn a user’s name). Protocol Mappers give administrators a middle path: expose precisely what is needed, to precisely the applications that need it, and nothing more.
2Where Protocol Mappers Live
Protocol Mappers don’t float around on their own — they are attached to specific building blocks inside Keycloak. Understanding those blocks makes everything else click.
Realm
A completely separate space inside Keycloak — like a separate office branch — with its own users, its own applications, and its own rules. One Keycloak server can host many realms.
Client
A registered application inside a realm — for example, a mobile banking app or an internal HR portal. Each client can receive its own token, shaped differently from another client’s token.
Client Scope
A reusable bundle of settings (including mappers) that can be attached to many clients at once, so you don’t repeat the same rule fifty times.
Protocol Mapper
A single rule, attached either directly to a client or to a client scope, that fills in one piece of the token.
Two places a mapper can be attached
Keycloak lets you attach a Protocol Mapper in two different places, and the choice matters a lot as a system grows:
Directly on a Client
- Quick to set up for a one-off need
- Only affects that single application
- Easy to lose track of as clients multiply
On a Client Scope (Shared)
- One change updates every client that uses the scope
- Keeps large organizations consistent
- Requires a bit more upfront planning to set up
A mapper attached directly to a client only shapes tokens issued for that client. If ten applications all need the same “department” field, attaching the same mapper ten separate times is a maintenance trap — a shared client scope solves this far more cleanly.
The protocol part of “Protocol Mapper”
Keycloak speaks more than one identity language, or “protocol.” The two most common are OpenID Connect (which produces tokens shaped like small pieces of JSON text) and SAML (an older standard used heavily in large enterprises, which produces XML documents called assertions). A Protocol Mapper always knows which protocol it is shaping output for, because a value that makes sense as a JSON field doesn’t automatically make sense as an XML attribute. This is why the word “Protocol” sits right in the name — the mapper’s job changes slightly depending on which language the token needs to be written in.
3How a Protocol Mapper Actually Works
Zooming in from “what it is” to “what happens the instant a token gets built.”
Every Protocol Mapper is really just three simple decisions bundled together: where does the value come from, what should the field be called in the token, and which part of the token should it appear in. Keycloak ships with several ready-made mapper kinds so administrators rarely have to invent a rule from scratch.
Where the value comes from
A mapper’s source is usually one of a handful of places:
A User Attribute
Custom data stored on the user’s profile, such as an employee ID or a preferred language, that an administrator or the user themselves has filled in.
A Built-in User Property
Standard fields Keycloak already tracks for every user, like first name, last name, or email address.
A Role
The permissions the user holds inside the realm or a specific client, such as “editor” or “billing-admin.”
A Group Membership
Which organizational groups the user belongs to, similar to being in a particular department or team.
A Fixed (Hardcoded) Value
A constant that never changes per user — useful for stamping every token from a given client with the same flag or tag.
A Custom Script or Claim
For situations the built-in options can’t cover, Keycloak allows a small custom rule to compute a value on the fly.
What the field should be called
Every mapper has a target name — the label the value will sit under inside the token. Applications read tokens by looking up these names, so a mismatched or misspelled name means the application simply won’t find the data, even though the mapper technically ran successfully.
Which part of the token it should appear in
This is one of the most important — and most frequently mishandled — decisions. A single login can produce more than one output at once, and a mapper must be told which of these outputs to write into.
| Token / Output | Typical Purpose |
|---|---|
| ID Token | Tells the application “here is who just logged in,” used right after authentication |
| Access Token | Presented on every later request to prove the user is still authorized |
| UserInfo Response | A separate lookup an application can make to fetch fresh profile details |
| SAML Assertion | The XML equivalent used by SAML-based applications instead of a JSON token |
Only include a value in the Access Token if something will actually check it there. Access tokens are sent on nearly every request, so keeping them lean keeps every request lighter and reduces what could leak if a token is ever exposed.
4From Login to Token: The Data Flow
A step-by-step walk through exactly when Protocol Mappers get invoked during a real login.
User Reaches the Application
Someone tries to open an app that requires login. The app redirects them to Keycloak instead of showing a login form itself.
User Authenticates
Keycloak checks the person’s credentials — password, one-time code, or any other configured method — and confirms who they are.
Keycloak Gathers the Ingredients
Keycloak loads the user’s profile, attributes, roles, and group memberships — everything a mapper might need to read from.
Every Applicable Mapper Runs
For the client involved in this login, Keycloak collects every mapper attached to it — directly or through a client scope — and runs each one in turn.
Tokens Are Assembled
Each mapper’s output is written into the token (or tokens) it was configured to target — ID Token, Access Token, UserInfo, or a SAML Assertion.
Tokens Are Signed and Handed Back
Keycloak digitally signs the finished tokens so the application can trust they weren’t tampered with, then sends them to the application.
Application Reads the Fields
The application opens the token, looks up the field names the mappers created, and uses those values to personalize the experience or make decisions.
sequenceDiagram
participant U as User
participant A as Application
participant K as Keycloak
U->>A: Tries to open the app
A->>K: Redirects for login
U->>K: Enters credentials
K->>K: Loads profile, roles, groups
K->>K: Runs every Protocol Mapper
K->>A: Sends back ID Token + Access Token
A->>A: Reads fields from the tokens
Picture an assembly line building a gift box. The person is verified at the door (login), then walks down a conveyor belt where different stations each add one item to the box — a card here, a ribbon there, a gift tag at the end. Each station is a Protocol Mapper. By the time the box reaches the exit, it contains exactly the items every station decided to add — no more, no less.
An important detail: mappers are re-evaluated every single time a new token is issued, including when an old token is quietly refreshed behind the scenes. This means a change to a user’s role or attribute is reflected the very next time a token is minted — it does not require the user to fully log out and log back in, only for their token to be refreshed, which typically happens automatically and fairly often.
5The Different Kinds of Protocol Mappers
Keycloak ships a toolbox of ready-made mapper types so administrators rarely need to build something exotic.
User Attribute Mapper
Copies a custom profile field (like “cost center”) straight into the token under a chosen name.
User Property Mapper
Copies a standard, built-in field — email, first name, username — into the token.
Role List / Group Membership Mapper
Lists the roles or groups the user belongs to, often used by applications to decide what a person can see or do.
Hardcoded Claim / Attribute Mapper
Inserts a fixed value that is the same for every user of a given client — handy for tagging tokens with an environment name or app version.
Audience Mapper
Tells the token which application (or applications) it is meant to be used by, so a token minted for one app can’t quietly be reused by another.
Script / Custom Mapper
Runs a small custom rule to compute a value that doesn’t come from a simple, direct field — for example, combining two attributes into one.
SAML-specific mappers
Because SAML assertions are structured differently from OpenID Connect tokens, Keycloak provides parallel mapper types tailored to XML output — such as mappers that shape “Attribute Statements” inside the assertion instead of JSON claims. Conceptually they do the same job; only the destination format differs.
6Weighing the Trade-offs
Protocol Mappers are powerful, but like any powerful tool, using them carelessly creates its own problems.
Advantages
- Applications get exactly the data they need without extra lookups
- Central control — one admin console shapes every application’s tokens
- Reusable through client scopes, avoiding repeated setup
- Works consistently across OpenID Connect and SAML applications
- Changes take effect on the very next token, no application redeploy needed
Disadvantages / Trade-offs
- Overstuffed tokens grow large and slow down every request that carries them
- Sensitive data placed carelessly can end up somewhere it shouldn’t be
- Too many one-off, client-specific mappers become hard to track over time
- Custom script mappers add a small amount of processing time to every login
7Keeping Protocol Mappers Secure
A token full of the wrong information is a quiet but serious security risk — here is what to watch for.
Tokens are often only lightly encrypted or not encrypted at all in transit contexts an administrator doesn’t always control — such as being stored in a browser or logged by a proxy. Anything placed inside a token should be treated as though it could eventually be seen by someone other than the intended application.
Minimizing exposure
The safest approach is to only expose what an application genuinely needs to function, and nothing extra “just in case.” This idea, often called the principle of least privilege, applies to tokens the same way it applies to file permissions or database access: fewer exposed fields means fewer things that can go wrong if a token is ever intercepted or mishandled.
The audience field matters more than it looks
The Audience Mapper deserves special attention because it prevents a subtle attack pattern: a token minted for Application A being replayed against Application B, which might trust the token without realizing it was never meant for it. Setting the audience correctly on every client is one of the cheapest, highest-value security habits an administrator can build.
Roles and groups need care too
Because role and group mappers can reveal an organization’s internal structure — team names, seniority levels, or which department someone belongs to — it is worth asking whether every application genuinely needs that level of detail, or whether a simpler yes/no flag would do the same job with less exposure.
Giving a courier a package with a full inventory list taped to the outside is convenient for the receiver, but it also tells anyone who glances at the box exactly what’s inside. Good token design is like sealing the box and only writing the delivery address — the receiving application asks for details separately, through a trusted channel, if it truly needs them.
8Watching What Your Mappers Do
Configuring a mapper is only half the job — knowing it’s behaving correctly in production is the other half.
What’s worth watching
Token Size Over Time
A steadily growing token size often signals mappers being added without anyone removing old ones — a slow accumulation worth periodically reviewing.
Failed or Slow Logins
A poorly written custom script mapper can quietly add delay to every single login, especially if it performs unnecessary extra lookups.
Admin Console Audit Events
Keycloak can record when mappers, client scopes, and clients are created or changed — a valuable trail when tracking down who altered a token’s shape and when.
Before rolling out a new mapper broadly, test it against a single client first and inspect the resulting token directly. Many identity tools can decode a token’s contents for a quick visual check that the field appeared exactly as expected.
Building a review habit
Treat the full list of mappers on a busy realm the way a good gardener treats a growing plant bed: periodically walk through it, ask whether every mapper is still earning its place, and prune anything left over from an application that no longer exists or a field nobody reads anymore.
9Patterns That Work, and Ones That Don’t
Some approaches to organizing mappers age gracefully; others quietly become a mess.
Approach
Group related mappers into named, purpose-built client scopes — for example, one scope for “basic profile” fields and a separate scope for “internal roles” — then attach only the scopes each application actually needs.
Why It Works
Changes are made once and ripple out consistently, and it’s obvious at a glance which applications receive which categories of data.
Problem
Copy-pasting the same set of mappers directly onto every new client, one by one, as the organization grows.
Why It’s Harmful
A single required change — renaming a field, fixing a bug, tightening security — now has to be repeated across dozens of clients, and it’s easy to miss one.
Correct Approach
Move the repeated mappers into a shared client scope and attach that scope wherever it’s needed instead.
Problem
Adding every available user attribute to the Access Token “just in case an application wants it someday.”
Why It’s Harmful
The Access Token is transmitted on nearly every request; bloated tokens waste bandwidth and needlessly expose data to services that never asked for it.
Correct Approach
Add fields to the Access Token only when a real, current need justifies it — use the UserInfo response for anything only fetched occasionally.
10Best Practices & Common Mistakes
A concise checklist gathered from the patterns above, framed as do’s and don’ts.
Name Fields Clearly
Use consistent, predictable names across mappers so developers integrating an application don’t have to guess.
Prefer Client Scopes
Default to shared scopes for anything more than one client will use, even if it feels like extra setup at first.
Set the Audience Explicitly
Never leave audience configuration to chance on a client handling sensitive operations.
Forgetting to Remove Old Mappers
When an application is retired, its dedicated mappers are often left behind, quietly bloating the realm.
Confusing Attributes with Properties
Trying to map a custom attribute using the built-in property mapper (or vice versa) results in an empty field that’s confusing to debug.
Targeting the Wrong Token
Placing a rarely used field in the Access Token instead of UserInfo adds unnecessary weight to every single request.
11Real-World & Industry Examples
A few grounded scenarios showing why organizations reach for Protocol Mappers in practice.
Internal HR Portal
An internal company tool needs to greet employees by name and show their department without a separate database lookup. A User Property Mapper supplies the name, and a User Attribute Mapper supplies the department — both arriving automatically inside the ID Token the moment the employee logs in.
Multi-Tenant SaaS Product
A software company serving many separate customer organizations uses a Group Membership Mapper so its application instantly knows which customer’s workspace a user belongs to, without a custom lookup table.
Banking Application Using SAML
A large financial institution’s older internal systems rely on SAML. Protocol Mappers translate the same underlying user roles into properly formatted SAML attribute statements, letting modern and legacy systems share one identity source.
Partner API Integration
An organization exposing an API to an external partner uses a Hardcoded Claim Mapper to stamp every token from that partner’s client with a fixed “partner-tier: standard” marker, letting backend services apply the correct rate limits without extra configuration.
flowchart TD
A["Realm: company.example"] --> B["Client Scope: basic-profile"]
A --> C["Client Scope: internal-roles"]
B --> D["Mapper: full name"]
B --> E["Mapper: email"]
C --> F["Mapper: role list"]
C --> G["Mapper: department attribute"]
B --> H["Client: HR Portal"]
C --> H
B --> I["Client: Partner API"]
12Frequently Asked Questions
Straightforward answers to the questions beginners ask most often.
No. Keycloak includes a small set of default mappers on the built-in client scopes already, covering common needs like basic profile info. You only add new mappers for fields that aren’t already covered.
Not immediately for tokens already issued, but the very next time their token is refreshed — which usually happens automatically in the background — the updated mapper takes effect.
Yes. A single mapper can be configured to appear in the ID Token, the Access Token, and the UserInfo response simultaneously, or only in whichever subset actually needs it.
Most mapper types simply omit the field from the token rather than including it blank, though this can vary slightly by mapper type and version.
No. Keycloak provides equivalent mapper types for SAML, shaping XML assertions instead of JSON tokens, so both protocol families benefit from the same underlying idea.
There’s no small fixed limit, but practically speaking, tokens grow with every mapper added — so the real constraint is keeping tokens lean rather than any hard technical cap.
13Summary and Key Takeaways
Protocol Mappers are the small, precise rules that shape what appears inside every token Keycloak issues. They read from a user’s properties, attributes, roles, or group memberships — or from a fixed value — and write that data into exactly the right output, whether that’s an ID Token, an Access Token, a UserInfo response, or a SAML Assertion. Used thoughtfully, through shared client scopes and lean, well-audited configurations, they let dozens of applications share one identity system while each receiving precisely the information it needs — no more, no less.
Key Takeaways
- A Protocol Mapper is a single rule — it decides one piece of data, one name, and one destination inside a token.
- Mappers attach to a Client or a Client Scope — scopes are the better choice whenever more than one application shares the same need.
- Every login re-runs the mappers — changes to user data flow into the very next token issued, no redeploy required.
- Not every field belongs in the Access Token — keep it lean, since it travels on nearly every request.
- The Audience Mapper is a security essential — it stops a token from being misused by an application it was never meant for.
- Regularly review your mapper list — old, forgotten mappers quietly bloat tokens and widen exposure over time.
- The same idea powers both OpenID Connect and SAML — only the output format changes, not the underlying concept.