Token Exchange in Keycloak: Trading One Token for Another, Safely

Token Exchange in Keycloak: Trading One Token for Another, Safely

A complete, no-code walkthrough of how Keycloak lets one trusted token be swapped for another — so services, gateways, and users can act on each other's behalf without ever sharing a password.

Imagine a busy hospital. A receptionist can’t walk into surgery and operate — but she can hand a verified patient file to a nurse, who hands a summarized version to a surgeon, who hands a specific instruction to an anesthesiologist. Each handoff carries only the information the next person actually needs, and each person’s identity stays visible in the paper trail. Token Exchange in Keycloak works the same way: it lets one part of your system take a token it was given and trade it in for a new, more appropriate token — scoped down, re-audienced, or re-issued for someone else — without ever touching a username or password. This post walks through what Token Exchange actually is, how Keycloak implements it internally, when to use it, when to avoid it, and how real companies use it to solve very real identity problems.

1What Is Token Exchange?

Before diagrams and architecture, let’s build a rock-solid mental model of the problem Token Exchange solves.

The problem: tokens are not meant to travel forever

When a user logs into an application through Keycloak, they receive an access token. That token proves “this request comes from this user, with these permissions, for this specific application.” The token is deliberately narrow — it’s meant for one audience (usually one client application) and one purpose. The moment that token needs to be used somewhere else — a different microservice, a different API, a different user context entirely — the narrow scope becomes a problem instead of a safety feature.

Simple Analogy

A concert wristband gets you into one venue for one night. It doesn’t get you into the after-party next door, even if the same company runs both events. Someone at the door needs to check your wristband and issue you a new, after-party-specific wristband. Token Exchange is that door — it checks your existing wristband and hands you a new one valid for the next place you need to go.

The formal definition

Token Exchange is a standardized OAuth 2.0 extension grant, defined in RFC 8693, that allows a party holding one security token to request a new, different token from an authorization server — typically with a different audience, a narrower scope, or a different subject. Keycloak implements this specification as one of its supported token grant types, alongside the more familiar password grant, client credentials grant, and authorization code grant.

i
Key Distinction

Token Exchange is not “refreshing” a token. A refresh token extends the lifetime of the same identity and audience. Token Exchange changes the shape of the token entirely — a new audience, a new scope, sometimes even a new subject.

Two kinds of tokens involved

Every Token Exchange request revolves around two token roles that are easy to confuse at first:

Role 1

Subject Token

The token representing the identity the new token should be issued for — usually the end user or the calling service. This is the “who” of the exchange.

Role 2

Actor Token

An optional second token representing the service performing the exchange on the subject’s behalf. This is the “who is doing the asking” of the exchange, used in delegation scenarios.

Most simple exchanges only need a subject token. Actor tokens appear when you need to preserve a chain of trust — for example, “Service B is acting for User X, but only because Service A vouched for it.”

Why the distinction matters in practice

Without this two-token model, a system has only two blunt options when a service needs to act for a user: either let the service fully impersonate the user with no trace of the service’s own involvement, or force the user to be present for every single downstream action, which defeats the point of automation. The subject/actor split gives a precise middle ground — the resulting token can prove both “this is genuinely about User X” and “this specific service is the one currently acting,” letting every downstream system make informed authorization decisions based on the full picture rather than a flattened, ambiguous identity.

!
Common Misconception

Token Exchange is not a way to bypass authentication. The exchanging party must already hold a valid token issued by the same (or a trusted federated) realm. It converts trust, it does not create trust out of nothing.

Where it fits among OAuth 2.0 grant types

Keycloak, like any standards-compliant authorization server, supports several ways of obtaining a token, each suited to a different kind of relationship between the requester and the resource being protected. Token Exchange is simply one more entry in that family — but it’s the only one whose entire purpose is transformation rather than initial issuance.

Grant TypeWho Holds the CredentialTypical Purpose
Authorization CodeEnd user, via browser redirectInteractive login for web and mobile apps
Client CredentialsThe service itselfService-to-service calls with no human involved
Refresh TokenThe original clientExtending an existing session’s lifetime
Token ExchangeAny party holding a valid tokenConverting one token into a differently scoped or audienced one

Notice the pattern: every other grant type answers “how do I get a token in the first place?” Token Exchange answers a different question entirely — “I already have a token; how do I get the right token for what I need to do next?” That distinction is the single most important thing to internalize before touching any configuration screen.

Why this needed its own specification

Before RFC 8693 existed, teams solved the same underlying problem — passing identity between services safely — with ad hoc, proprietary mechanisms: shared secrets between internal services, custom “impersonation” API endpoints, or simply forwarding the original token everywhere and hoping every downstream service behaved responsibly. Each of these approaches worked, but none of them were interoperable, auditable in a standard way, or safe by default. Standardizing the exchange as a first-class OAuth 2.0 grant type meant tooling, libraries, and identity providers across the industry could implement the same behavior predictably, and Keycloak’s implementation is one of the most complete open-source realizations of that specification available today.

2Architecture & Components

Token Exchange doesn’t live in isolation — it sits at the intersection of several Keycloak building blocks working together.

The realm as the trust boundary

In Keycloak, a realm is an isolated space of users, clients, and configuration. Token Exchange, by default, operates within a single realm — the token issuer and the token requester both trust the same realm’s signing keys and identity data. Cross-realm exchange is possible but requires explicit trust configuration, since Keycloak treats realms as hard security boundaries by design.

Clients and their permissions

A client in Keycloak represents an application or service registered to use the realm. For Token Exchange to work, the requesting client needs a specific permission granted through Keycloak’s fine-grained authorization services — it isn’t enabled by a simple checkbox on older or default configurations, precisely because it’s a sensitive capability that lets one client mint tokens intended for another.

Component

Token Endpoint

The same OAuth 2.0 endpoint used for every other grant type, distinguished by a special grant_type value identifying it as an exchange request.

Component

Client Policies

Rules attached to a client defining exactly which other clients it may exchange tokens for, and under what conditions.

Component

Identity Provider Broker

The subsystem that allows a token issued by an external identity provider to be exchanged for a native Keycloak token, and vice versa.

Component

Token Introspection

The mechanism Keycloak uses internally to validate that a presented subject or actor token is genuine, unexpired, and issued by a trusted source.

How the pieces fit together

Picture Keycloak as a train station with several platforms. Each client is a train line. A passenger (a token) arriving on Platform A cannot simply walk onto a train on Platform D — a station agent (the token exchange authorization logic) checks whether that transfer is permitted, based on posted rules (client policies), before issuing a new ticket (the exchanged token) for the new platform.

flowchart LR
    U[User / Service
holding Subject Token] -->|presents token| TE[Token Endpoint
grant_type=token-exchange] TE --> POLICY{Client Exchange
Policy Check} POLICY -->|allowed| MINT[Token Service
mints new token] POLICY -->|denied| REJECT[403 / invalid_grant] MINT --> NEW[New Access Token
new audience / scope / subject] IDP[External Identity Provider] -.federated tokens.-> TE
FIG 1 — How a subject token flows through Keycloak’s exchange policy check to become a new token

Realm settings that gate the feature

Because Token Exchange is powerful enough to let one service impersonate another’s audience, Keycloak historically shipped it as a preview or opt-in feature, controlled through realm-level feature flags and admin console permission grants. Administrators must deliberately enable it and then deliberately grant the exchange permission per client pair — a two-layer safety switch that prevents it from being silently available.

Protocol mappers and client scopes

Once an exchange is authorized, the actual shape of the new token — which claims it carries, which roles it exposes, which custom attributes appear — is determined by the target client’s protocol mappers and assigned client scopes, exactly as if the target client had issued the token through a normal login flow. This is a deliberate design choice: it means the target service defines what “a valid token for me” looks like, and the exchange mechanism simply satisfies that contract rather than inventing a separate token format for exchanged identities.

Simple Analogy

Think of protocol mappers as a customs form. No matter which country a traveler is arriving from, the destination country’s customs office decides what information gets recorded on entry. The traveler’s original documents (the subject token) inform the process, but the destination’s own rules (the target client’s mappers) shape the final paperwork (the new token).

The role of the admin console versus automation

In smaller deployments, administrators typically configure exchange permissions by hand through the Keycloak admin console, using the fine-grained authorization tab on each client. In larger organizations running dozens or hundreds of services, this configuration is usually managed as code — expressed declaratively and applied through Keycloak’s realm export/import tooling or a configuration-as-code operator — so that “which client can exchange for which audience” is reviewable in a pull request rather than buried in a UI screen only a few administrators can see.

Identity provider brokering in more depth

Many organizations don’t authenticate every user directly against Keycloak’s own user store. Instead, Keycloak acts as a broker in front of external identity providers — a corporate directory, a social login provider, or a partner organization’s own authorization server. When a user logs in through one of these external providers, Keycloak’s broker exchanges the external provider’s token for a Keycloak-native one behind the scenes, so that every internal service only ever has to understand one token format, one signing key set, and one set of claim conventions — regardless of how many different front doors users actually walked through.

Without Brokering

N Token Formats

Every internal service would need to understand and validate tokens from every external identity provider directly — a maintenance burden that grows with every new provider added.

With Brokering

1 Token Format

Internal services validate only Keycloak-issued tokens; the complexity of federating with external providers stays contained entirely within the broker.

This is why identity federation bridging (introduced in Chapter 5) is really just a specialized application of the same exchange machinery described in this chapter — the “external identity provider” is simply treated as another trusted issuer whose tokens Keycloak knows how to validate and convert.

3Internal Working

What actually happens inside Keycloak the moment an exchange request lands on the token endpoint?

1

Request arrives at the token endpoint

The requesting client authenticates itself (usually with a client secret or private key) and submits the subject token, the desired audience, and optionally the actor token and requested scopes.

2

Client authentication is verified

Keycloak confirms the requesting client is who it claims to be — this is the same authentication step used by every other grant type, ensuring anonymous parties can’t request exchanges.

3

Subject and actor tokens are validated

The presented tokens are checked for a valid signature, correct issuer, and unexpired lifetime — exactly as if they were being used directly against a protected API.

4

Exchange policy evaluation

Keycloak checks whether the requesting client is explicitly permitted to exchange tokens for the requested target audience. This is enforced through the fine-grained authorization policies attached to the target client.

5

Claim mapping and scope narrowing

The new token is built from the subject’s identity claims, filtered and mapped according to the target client’s protocol mappers, and its scope is narrowed to only what was requested and permitted.

6

New token is signed and returned

Keycloak signs the freshly minted token with the realm’s active signing key and returns it in the standard OAuth 2.0 token response shape, just like any other grant.

Simple Analogy

Think of a passport control counter at an airport that also issues connecting visas. The officer checks your existing passport (subject token validation), checks whether your travel agency is authorized to request that visa on your behalf (exchange policy), stamps in only the permissions your onward trip needs (scope narrowing), and hands you a fresh, purpose-specific document (new token) — all without ever asking you to re-prove your original identity from scratch.

Where the actor token changes the picture

When an actor token is present, Keycloak embeds an additional claim in the resulting token that records “this identity is acting on behalf of that identity.” This preserves an audit trail through the entire delegation chain — critical for systems where a support tool, an automation service, or an API gateway needs to act as a user without literally becoming indistinguishable from that user.

i
Under the Hood

The resulting token typically carries both the original subject’s identity and an “act as” claim identifying the delegating party — so downstream services can tell the difference between “the user did this directly” and “a service did this for the user.”

How claim mapping decisions get made

Not every claim on the subject token automatically survives into the new token. Keycloak evaluates the target client’s configured protocol mappers one by one, and each mapper decides independently whether to copy a claim across, transform it, or omit it entirely. This means a target service can, for example, receive the user’s unique identifier and role claims while never seeing an email address or a phone number that the original token carried — a deliberate narrowing that supports data-minimization requirements many organizations must meet for privacy compliance.

Simple Analogy

Think of a translator working between two diplomats. The translator doesn’t repeat every word verbatim — they convey the meaning that matters to the listener, in the vocabulary the listener understands, and quietly drop the small talk that doesn’t need translating. Protocol mappers do the same job for claims moving from a subject token into an exchanged token.

Scope negotiation during the exchange

A requesting client can ask for a specific, narrower scope than the subject token originally carried — but it can never ask for a broader one than either the subject token or the target client’s own configuration allows. Keycloak computes the effective scope as the intersection of what was requested, what the subject token was entitled to, and what the target client is configured to grant. This three-way intersection is what makes downscoping a hard security guarantee rather than a polite convention that a misbehaving client could simply ignore.

4Data Flow & Lifecycle

Let’s trace a full request end to end, using a realistic scenario: an API gateway exchanging a user’s token to call a downstream microservice.

sequenceDiagram
    participant User
    participant Gateway as API Gateway
    participant KC as Keycloak Token Endpoint
    participant Micro as Downstream Microservice

    User->>Gateway: Request with original access token
    Gateway->>KC: token-exchange request
(subject_token = user's token,
audience = microservice) KC->>KC: Validate client + subject token KC->>KC: Check exchange policy for Gateway → Microservice KC-->>Gateway: New scoped access token for Microservice Gateway->>Micro: Call API with new token Micro-->>Gateway: Response Gateway-->>User: Final response
FIG 2 — A gateway exchanges a broad user token for a narrow, service-specific token before calling downstream

Lifecycle of the exchanged token

The new token follows the same lifecycle rules as any other Keycloak-issued token: it has its own expiration, its own audience restriction, and its own signature. Critically, it does not inherit the original token’s remaining lifetime automatically — Keycloak issues it with a fresh, independently configured lifespan appropriate to the target client, which can be shorter than the original for tighter security.

Stage

Issued

The new token is minted with its own claims, audience, and expiry, separate from the original subject token’s timeline.

Stage

Used

The receiving service validates it exactly like any other bearer token — checking signature, audience, and expiry.

Stage

Expired

Once expired, a new exchange must be performed from a still-valid subject token; the exchanged token itself is not typically refreshable on its own.

Stage

Revoked

If the original subject’s session is revoked, subsequent exchange attempts using that subject token will fail at the validation step.

!
Lifecycle Trap

Because the exchanged token is independent once issued, revoking the original session does not retroactively invalidate tokens that were already exchanged and are still within their own validity window — a nuance teams often overlook when designing “instant logout” behavior.

Handling the revocation gap

Systems that need true instant logout despite this independence typically layer an additional check on top of token expiry: a fast, centralized revocation list or session-status lookup that downstream services consult before honoring a token, even one that hasn’t technically expired yet. This adds operational cost — every request now needs an extra lookup — but for use cases like “immediately lock out a terminated employee across every connected system,” it closes the gap that short token lifetimes alone can’t fully address. The trade-off is a deliberate one: shorter-lived exchanged tokens shrink the revocation gap without eliminating it, while an active revocation check closes it entirely at the cost of an additional lookup on every request.

Chained exchanges and their lifecycle implications

In more elaborate architectures, a token might be exchanged more than once as it travels through several hops — a gateway exchanges the original user token for a service token, and that service later exchanges its own token again before calling a third, deeper service. Each hop in this chain has its own independent lifecycle, and each hop’s actor claims should ideally accumulate rather than overwrite one another, so the full path an identity traveled remains reconstructable from the final token alone.

5Common Exchange Patterns

Token Exchange isn’t a single use case — it’s a mechanism that supports several distinct patterns, each solving a different problem.

Impersonation

A trusted service, such as an internal admin tool, exchanges its own service token to obtain a token that represents a specific end user — useful for “log in as this customer” support workflows, always under tight audit controls.

Delegation

A service acts on a user’s behalf while preserving both identities in the resulting token, so downstream systems can distinguish “the user did this” from “a service did this for the user.”

Audience Restriction / Downscoping

A broadly scoped token from a frontend is exchanged for a narrowly scoped, single-purpose token before being forwarded to a specific backend service — reducing what a compromised downstream service could do with a leaked token.

Identity Federation Bridging

A token issued by an external identity provider (through Keycloak’s broker) is exchanged for a native Keycloak-issued token, letting internal services trust one consistent token format regardless of where the user originally authenticated.

Comparing the patterns side by side

PatternWho InitiatesIdentity in ResultTypical Use
ImpersonationAdmin/support serviceTarget user onlySupport tooling, troubleshooting
DelegationActing serviceUser + acting service (chained)Automation acting for a user
DownscopingGateway/BFFSame user, narrower scopeMicroservice call chains
Federation BridgingBroker flowExternally authenticated userMulti-IdP environments
“Token Exchange doesn’t create new trust — it reshapes existing trust into the form the next hop actually needs.”

6Token Exchange vs. the Alternatives

It helps to see Token Exchange next to the approaches teams reach for when they haven’t adopted it yet — and understand exactly what each alternative gives up.

Alternative

Token Forwarding

Simply passing the same original token to every downstream service. Simple to implement, but every service ends up with far more scope and audience access than it actually needs.

Alternative

Admin Impersonation API

Keycloak’s separate admin impersonation endpoint lets an administrator obtain a session as another user directly. Powerful, but coarse — it’s built for admin tooling, not general service-to-service delegation.

Alternative

Shared Service Secrets

Internal services authenticate to each other with a shared API key instead of a token at all. This sidesteps identity propagation entirely, losing any notion of “on behalf of which user.”

Alternative

Custom Security Token Service

Some organizations build a bespoke internal service that mints new tokens after checking a caller’s original credentials. This reinvents what Token Exchange already standardizes, at the cost of building and maintaining it yourself.

ApproachPreserves Identity?Scope Narrowing?Standardized?
Token ForwardingYesNoN/A
Admin Impersonation APIYesNoKeycloak-specific
Shared Service SecretsNoN/ANo
Custom Security Token ServiceDepends on designDepends on designNo
Token Exchange (RFC 8693)YesYesYes

The pattern across every alternative is the same: they each solve part of the problem while quietly giving up something else — either identity, or scope discipline, or interoperability. Token Exchange is attractive precisely because it’s the only option on this list that keeps all three at once, backed by a specification other authorization servers and client libraries already understand.

Migrating from an alternative to Token Exchange

Teams moving away from token forwarding or a custom-built security token service usually don’t need to redesign their entire architecture — they need to identify the specific boundaries where identity currently crosses from one service to another with too much scope attached, and introduce an exchange step at exactly those boundaries. The rest of the system, including how users originally authenticate and how tokens are validated on each service, typically stays unchanged, which is part of why adopting the standard tends to be more incremental than teams initially expect.

7Advantages, Disadvantages & Trade-offs

Like every powerful mechanism, Token Exchange trades convenience for complexity in specific, predictable ways.

Advantages

  • Eliminates the need to pass around long-lived, broadly scoped tokens between services
  • Preserves an auditable chain of “who acted for whom” through actor token claims
  • Standardized by RFC 8693, so it interoperates with other compliant authorization servers
  • Enables least-privilege architectures where each hop gets only the scope it needs
  • Bridges external identity providers into a single internal token format

Disadvantages / Trade-offs

  • Adds an extra network round trip to the authorization server for every exchange
  • Configuration complexity grows quickly as the number of client-to-client exchange permissions increases
  • Exchanged tokens don’t automatically inherit revocation of the original session
  • Historically shipped as a preview feature in some Keycloak versions, requiring careful version-checking before relying on it in production
Simple Analogy

Every currency exchange booth at an airport is convenient, but each transaction takes time and carries a small fee. Token Exchange is the same trade: you gain safer, better-scoped credentials at every hop, but you pay for it in an extra round trip and in the operational discipline of managing exchange policies correctly.

When the trade-off tips in your favor

The extra round trip matters most in latency-sensitive, high-throughput paths — a payments API processing thousands of requests per second will feel every additional hop to the token endpoint. In those cases, teams often cache exchanged tokens for their short remaining lifetime rather than exchanging on every single call, trading a small amount of staleness for significantly reduced load on the authorization server.

When it’s not worth adopting yet

For a small system with two or three services that already fully trust each other and share the same deployment boundary, the operational overhead of configuring and reviewing exchange policies may outweigh the security benefit. Token Exchange earns its complexity in systems with many independently deployed services, multiple identity sources, or a genuine need to prove — not just assume — who acted on whose behalf.

8Security Considerations

Because Token Exchange sits right at the boundary of “who is allowed to act as whom,” its security posture deserves special attention.

The confused deputy problem

A classic risk in delegated systems is the “confused deputy” — a trusted service tricked into using its authority on behalf of an untrusted request. Token Exchange mitigates this by requiring explicit, per-client-pair authorization before any exchange succeeds, rather than trusting any authenticated client to exchange for any audience.

Risk

Overly Broad Exchange Policies

Granting a client permission to exchange for “any” audience defeats the purpose of scoped trust and should be avoided.

Risk

Long-Lived Exchanged Tokens

Issuing exchanged tokens with excessive lifetimes reduces the security benefit of downscoping.

Risk

Missing Actor Claims

Omitting actor tokens in delegation scenarios erases the audit trail of who really performed an action.

Risk

Unrevoked Session Windows

Because exchanged tokens are independent, a compromised original session can still produce valid downstream tokens until it’s fully revoked.

!
Security Reminder

Token Exchange should always be paired with short-lived tokens, tight audience restriction, and mandatory TLS on the token endpoint — it is not a substitute for those baseline protections, only a complement to them.

Threat modeling exchange-enabled clients

Any client granted exchange permission should be treated, from a threat-modeling perspective, as a more privileged actor than a client that only ever consumes tokens for itself. A compromise of that client’s credentials doesn’t just expose one service’s data — it exposes every audience that client is permitted to exchange for. This is exactly why the principle of least privilege matters so much more here than in ordinary client configuration: every additional exchange permission granted to a client widens the blast radius of a single credential compromise.

Auditing and traceability

Every exchange request is an event worth recording: who requested it, for whom, for what audience, and whether it succeeded. Because exchanges chain identities together, good audit logging is what turns Token Exchange from a security risk into a security asset — it’s what lets an investigator later reconstruct exactly which service acted on which user’s behalf and when.

Defense in depth around the exchange endpoint

Because the token endpoint becomes a higher-value target once it’s capable of minting differently audienced tokens, it deserves the same defensive layering as any other critical authentication surface: strict TLS enforcement, rate limiting on exchange attempts per client, alerting on repeated denial patterns that could indicate probing, and periodic rotation of client secrets used to authenticate exchange requests. None of these are unique to Token Exchange, but skipping them is a more expensive mistake once exchange is enabled, simply because a single compromised client credential now has a wider blast radius.

i
Practical Safeguard

Consider requiring mutual TLS or signed JWT client authentication (rather than a static client secret) for any client permitted to perform token exchanges — the exchange capability is exactly the kind of privilege where a leaked shared secret does disproportionate damage.

9Monitoring, Logging & Metrics

Operating Token Exchange in production means treating it as a first-class, observable subsystem — not a background detail.

3
core signals: rate, denial reason, latency
1:1
exchange event → audit log entry
2
identities per delegated exchange to trace

What to watch

Metric

Exchange Success Rate

A sudden drop can indicate a broken client policy, an expired trust relationship, or a misconfigured audience.

Metric

Denial Reasons

Tracking why exchanges are rejected (policy denial, invalid subject token, unknown audience) helps distinguish attacks from misconfiguration.

Metric

Exchange Volume by Client Pair

An unexpected spike from a client that rarely exchanges tokens is a strong signal worth investigating.

Metric

Token Endpoint Latency

Since every exchange adds a round trip, latency on this endpoint has a direct, multiplied effect on end-to-end request time.

What to log

At minimum, a healthy audit trail records the requesting client, the subject token’s identity, the actor token’s identity (if present), the requested audience and scope, and the outcome. This log is what makes delegation chains reconstructable after the fact — essential for both security investigations and compliance reporting.

Simple Analogy

A currency exchange counter that doesn’t record transactions can’t help investigators trace where money came from or went. The same is true for a token exchange service — without logs, a chain of delegated identity is just as untraceable as unrecorded cash.

Building a useful exchange dashboard

A single dashboard that plots exchange volume, success rate, and denial reasons over time — broken down by client pair — turns Token Exchange from an invisible background process into something an operations team can actually reason about during an incident. When something goes wrong elsewhere in the system, being able to quickly check “did the exchange path behave normally during this window?” often shortens investigation time considerably, since it either rules exchange in or out as a contributing factor within minutes rather than hours.

Alerting thresholds worth setting

Rather than alerting on every single denied exchange — which can be noisy, since legitimate misconfigurations happen during normal development — most teams alert on sustained deviations from a baseline: a denial rate that climbs well above its historical average, a previously unseen client attempting to exchange tokens, or a sudden concentration of exchange requests for an unusually sensitive audience. These pattern-based alerts catch genuine problems without drowning the team in noise from routine, expected failures.

10Design Patterns & Anti-Patterns

Some ways of using Token Exchange age well. Others quietly become security incidents.

ANTI-PATTERN-01 Avoid
Problem

Granting a gateway client blanket exchange permission for every downstream audience “to save configuration time.”

Why It’s Harmful

It turns the gateway into a single point of failure — if it’s compromised, an attacker can mint tokens for any service in the system, defeating the entire purpose of scoped exchange.

Correct Approach

Grant exchange permission per audience explicitly, and review the list of permitted audiences as part of normal access reviews.

ANTI-PATTERN-02 Avoid
Problem

Using Token Exchange purely to extend a token’s lifetime rather than to change its audience or scope.

Why It’s Harmful

This conflates two different mechanisms — refresh tokens exist for lifetime extension. Using exchange this way adds unnecessary complexity and can mask a poorly designed token lifetime strategy.

Correct Approach

Use refresh tokens for lifetime extension of the same identity and audience; reserve exchange for genuine audience or subject changes.

Patterns worth adopting

Gateway-Side Downscoping

Perform the exchange once at the edge (API gateway or backend-for-frontend) so every downstream microservice only ever sees narrowly scoped, purpose-specific tokens.

Explicit Actor Chains for Support Tools

Always include an actor token when a support or admin tool impersonates a user, so the resulting token’s claims make the delegation visible to every downstream consumer and auditor.

Short-Lived Exchanged Tokens by Default

Configure exchanged tokens with shorter lifespans than the originals, since they typically only need to survive a single downstream call chain.

ANTI-PATTERN-03 Avoid
Problem

Treating an exchanged, downscoped token as equivalent to the original in security value, and storing or logging it as loosely as a low-sensitivity value.

Why It’s Harmful

A downscoped token is still a valid bearer credential for its narrower audience. Handling it carelessly — logging it in plaintext, storing it in an insecure cache — still exposes a real, usable credential, even if a smaller one.

Correct Approach

Apply the same secret-handling discipline to exchanged tokens as to any other bearer token: never log them in full, encrypt them at rest if cached, and scope their storage lifetime to match their actual expiry.

A pattern worth naming: the exchange boundary

Mature architectures tend to converge on a small, well-defined set of places where exchange happens — often just the API gateway and perhaps one internal identity-bridging service — rather than letting every service independently decide to exchange tokens whenever convenient. Concentrating exchange logic at a few well-audited boundaries makes the entire system’s trust model dramatically easier to reason about, review, and test.

11Best Practices & Common Mistakes

A checklist-style chapter distilling the operational wisdom from the sections above.

Best PracticeCommon Mistake It Prevents
Grant exchange permissions per specific client pairBlanket “allow all” exchange policies
Always include actor tokens in delegation flowsLosing the audit trail of “who acted for whom”
Set shorter lifespans on exchanged tokensExchanged tokens outliving their real usage window
Log every exchange attempt, success or failureNo way to reconstruct incidents after the fact
Pair exchange with active session revocation checksAssuming revoking a session invalidates already-exchanged tokens
Review the Keycloak version’s feature-flag status for exchangeRelying on a preview feature without understanding its stability guarantees
i
Operational Tip

Treat the list of “which client can exchange for which audience” as a piece of security configuration deserving the same review rigor as firewall rules — because functionally, that’s exactly what it is.

Rolling out Token Exchange incrementally

Teams introducing exchange into an existing system rarely flip it on everywhere at once. A common rollout sequence starts with a single, low-risk internal service pair — often the API gateway talking to one non-critical downstream service — running the exchange path in parallel with the old token-forwarding behavior for a period of observation. Only once the exchange path has proven reliable, with clean logs and no unexpected denials, does the team extend the pattern to additional service pairs, gradually retiring the older, broader-trust approach.

Testing exchange configuration before it reaches production

Because exchange policies are effectively security rules, they deserve the same automated testing rigor as any other access-control logic: verifying that permitted client pairs succeed, that unlisted pairs are correctly denied, and that scope narrowing behaves as expected for a range of requested scopes. Catching a misconfigured policy in a test environment is far cheaper than discovering it in production, either as a broken integration or — worse — as an unintentionally permissive exchange path that nobody reviewed.

Documenting the trust graph

As the number of clients grows, it becomes easy to lose track of which service can exchange tokens for which other service. Maintaining a simple, current diagram or table of this trust graph — reviewed whenever a new exchange permission is added — turns an invisible, implicit trust relationship into something a new team member, an auditor, or an incident responder can understand at a glance.

12Real-World & Industry Examples

Token Exchange shows up in industries wherever one service needs to safely act on behalf of another identity.

Customer Support Impersonation

Support platforms use exchange-based impersonation so an agent’s tooling can act as a specific customer for troubleshooting, while every action remains attributable to the agent through actor claims — a pattern common across SaaS support desks.

API Gateways in Microservice Architectures

Organizations running many internal microservices commonly exchange a broad, user-facing token at the gateway for narrow, service-specific tokens before fanning requests out internally — limiting blast radius if any single microservice is compromised.

Multi-Tenant SaaS Platforms

Platforms that federate authentication across multiple external identity providers use exchange to normalize every login into one consistent internal token shape, regardless of which provider the tenant’s users originally authenticated with.

Automation and Bot Services

Workflow automation tools that need to perform actions “as” a user — for example, triggering a report generation job — use delegated exchange so the resulting audit log clearly shows both the automation and the human who authorized it.

Regulated Financial Services

Banking and fintech platforms, where every action must be traceable to an accountable identity, use actor-token delegation so that automated fraud checks, batch settlement jobs, or teller-assisted transactions all carry a verifiable record of both the acting system and the underlying customer or employee identity.

Healthcare Interoperability

Healthcare systems that integrate multiple clinical applications behind a single patient-facing portal use downscoping exchanges to ensure that a token granting broad portal access is never the same token presented to a narrow, specialized clinical records service — keeping each system’s exposure limited to exactly what it needs to do its job.

Across every one of these industries, the underlying motivation is identical: a system granted broad trust at one layer should never be forced to pass that same broad trust, unmodified, to every layer beneath it. Token Exchange is simply the standardized way of enforcing that principle at the protocol level rather than hoping every team remembers to enforce it in application code.

“The organizations that get Token Exchange right treat every exchange as a recorded decision, not a silent handoff.”

13Frequently Asked Questions

Q1Is Token Exchange the same as refreshing a token?

No. Refreshing extends the lifetime of the same identity and audience. Token Exchange produces a new token that can have a different audience, scope, or even subject entirely.

Q2Do I need an actor token for every exchange?

No — actor tokens are only needed when you want to preserve a delegation chain, such as a service acting on a user’s behalf. Simple downscoping exchanges often only need a subject token.

Q3Does revoking a user’s session invalidate tokens already exchanged from it?

Not automatically. Exchanged tokens are independent once issued, so they remain valid until their own expiry unless additional revocation checks are specifically enforced.

Q4Can Token Exchange work across two different realms?

It’s possible, but it requires explicit cross-realm trust configuration, since realms are treated as strong isolation boundaries by default.

Q5Why does my Keycloak installation not show Token Exchange as available?

In many Keycloak versions, this capability has shipped as a preview feature that must be explicitly enabled at the realm or server level before client exchange permissions can even be configured.

Q6Is Token Exchange only useful for microservices?

No — it’s equally valuable for identity federation bridging, support-tool impersonation, and any scenario where one trusted party needs to obtain a differently scoped or differently audienced token.

Q7Does the exchanged token expose the original subject token to the downstream service?

No — the downstream service only ever sees the newly issued token. The original subject token is used purely as proof of identity during the exchange call and is never forwarded onward.

Q8Can a single exchange request change both the audience and the subject at once?

Yes — impersonation-style exchanges commonly do both: the requesting client authenticates as itself, presents a subject token for a different user, and requests a token audienced for yet another downstream service, all in one exchange call.

14Summary and Key Takeaways

Token Exchange in Keycloak is the mechanism that lets a trusted party trade one token for another — reshaping identity, audience, and scope without ever touching a password. It turns broad, general-purpose tokens into narrow, purpose-built ones at exactly the boundaries where that narrowing matters most: between a gateway and its microservices, between a support tool and the customer it’s helping, or between two identity providers meeting in the same realm. Used with explicit per-client policies, short-lived exchanged tokens, and disciplined audit logging, it becomes one of the most effective tools for building a least-privilege, fully traceable identity architecture.

The teams that get the most value from it tend to share a common habit: they treat every exchange permission as a deliberate architectural decision rather than a convenience toggle, they concentrate exchange logic at a small number of well-understood boundaries, and they instrument the exchange path as carefully as they would any other security-critical service. None of that requires exotic tooling — it requires treating the token endpoint’s exchange capability with the same seriousness as any other place in the system where trust changes hands.

Key Takeaways

  • Token Exchange is RFC 8693 — a standardized OAuth 2.0 grant, not a Keycloak-specific invention.
  • Subject and actor tokens — the subject is who the new token represents; the actor is who’s requesting it on their behalf.
  • It reshapes trust, it doesn’t create it — the requesting client must already hold a valid, verifiable token.
  • Exchanged tokens are independent — they don’t automatically inherit revocation from the original session.
  • Explicit per-client-pair policies are the difference between a secure exchange setup and a confused-deputy risk.
  • Delegation chains need actor claims — without them, you lose the audit trail of who really acted.
  • Downscoping at the edge — exchanging once at a gateway keeps every downstream service’s tokens narrow and purpose-specific.