Keycloak token exchange (RFC 8693) for service-to-service delegation
Keycloak implements token exchange under RFC 8693, and the design question is which exchange pattern fits the call chain you are building. The typical starting point is a frontend that holds an access token issued for one API, while a downstream service needs a token scoped to a different audience, or needs to act on the user's behalf. Before you configure anything, write down for each hop who the caller is, which user (if any) must be preserved, and which audience the downstream service will check. Those three answers decide whether you need delegation, impersonation-style exchange, or something simpler.
Teams often reach for token exchange too early. If a service calls another service with its own identity and no user context is needed, a client credentials grant with a dedicated client and a narrow scope is usually enough, and it is easier to audit. If the frontend's token already carries the right audience once the API is registered correctly, an audience mapper on the client may remove the need for an exchange at all. Token exchange earns its place when the downstream token must carry the user's identity, a different audience, or reduced scopes, and when you need a clear record of who delegated what to whom. Confirm in the Keycloak documentation for your release which token exchange features are supported in the standard flow and which still depend on the deprecated legacy version, since the two behave differently and the legacy one should not anchor a new design.
Whichever pattern you choose, plan the controls before the first exchange is permitted. Decide which clients may request exchanges, restrict the audiences they can target, keep token lifetimes for exchanged tokens short, and test that a token issued for one service is rejected by another. Ask your implementation partner or internal team to document each allowed exchange as a pair of source and target clients, with the owner, the reason and the review date. Consult the Keycloak server administration guide for the current configuration steps, and verify each exchange with an illustrative test chain before connecting production services.
Keycloak validates the subject token before any new token reaches the target
The flow starts at the calling client, which sends its subject token and a token exchange request to the Keycloak token endpoint. Inside the Keycloak trust boundary, Keycloak validates the subject token and checks whether the client's exchange policy allows the requested target audience. If the checks pass, Keycloak issues a new token scoped to that target. The client forwards the returned token to the target service, which must validate it before acting on the request. Trust moves from Keycloak to the downstream API at that hand-off, so the target should check the token's aud, issuer and signature.
Trust moves from Keycloak to the target service at the returned token.
Delegation patterns for service-to-service calls
In this pattern, a service exchanges a user's token for a new token that identifies the service's caller as the user itself, with no record that another party acted. It is the simplest pattern to build because the downstream API sees one subject and applies that user's permissions. It fits narrow cases such as a trusted batch job that must read data exactly as the user would see it. The main risk is that the downstream service cannot tell a delegated request from a direct user request, so any compromise of the calling service carries the user's full rights.
- Downstream checks: confirm the token's audience names this API and that the requested scope is limited to what the job needs.
- Scope limits: request only the scopes the exchange requires, not the user's full set of client roles.
- Logging: make sure the API logs the subject and the exchange client so that actions remain traceable.
- Lifetime: keep the exchanged token short-lived and avoid refresh tokens for it.
- Confirm support: check in your Keycloak version whether this exchange form is available under standard token exchange or depends on the legacy feature.
Before adopting this pattern, have the security team agree that losing actor identity in the token is acceptable for each workflow.
Here the exchanged token keeps the original user as the subject and records the calling service as the actor, so both identities are visible to the downstream API. This follows the delegation model described in RFC 8693, where the act claim carries the acting party. It fits cases where an API must authorize based on the user's rights while still knowing that a specific service made the call. The main risk is that downstream services often ignore the actor claim, which turns delegation into impersonation without anyone noticing.
- Downstream checks: require the act claim on delegated requests and reject tokens whose actor is not on an approved list.
- Actor allow list: restrict which clients may appear as actors for each API.
- Chained delegation: decide whether nested act claims are allowed and how deep they may go.
- Audit trail: log both subject and actor for every request so investigations can separate user activity from service activity.
- Confirm support: verify how your Keycloak release populates the actor claim and whether you can control it through client configuration.
Test a request where the actor claim is removed or altered to confirm that the downstream API refuses it.
Audience swapping exchanges a token issued for one API into a token for another internal API, usually keeping the same user and scopes while changing the audience. This suits microservice chains where a gateway receives a token for the front-end API and needs a token for a back-end service without asking the user to sign in again. The main risk is that a token that is valid everywhere inside the network invites lateral movement, because one stolen token can reach several services.
- Downstream checks: reject any token whose audience does not name this service, even when the signature is valid.
- Scope narrowing: request a smaller scope set for each hop so that the exchanged token grants less than the original.
- Hop limits: keep chains short and document which services may exchange into which audiences.
- Client policy: restrict which clients may request exchanges to specific target audiences.
- Confirm support: check the audience and scope parameters your Keycloak version accepts in standard token exchange.
Run a test where a token for one service is presented to another to confirm that each API rejects it.
Most designs combine patterns, so the decision starts with what the downstream service must know about the caller. If it only needs the user's permissions, audience swapping with narrowed scopes is usually the most contained choice. If it must enforce that a specific service acted for a user, delegation with subject and actor is the right fit. Impersonation-style exchange should be reserved for tightly controlled jobs where the actor's identity does not change the authorization decision. Document the pattern for each API so that reviewers can test it against the stated rule.
- Decision question: does the API need to know which service acted, which user is affected, or both?
- Default posture: start with the narrowest scope and the shortest lifetime, then widen only with a documented reason.
- Ownership: assign each exchange path to a named application owner.
- Review cycle: revisit allowed exchanges whenever a service is added or its scope changes.
- Confirm support: ask Keycloak and your distribution vendor which exchange forms are supported in the release you run before committing to a design.
Write the chosen pattern into the design record for each service so that security testing can check it.
Token exchange configuration options and when each fits
This table compares the main choices for Keycloak token exchange: which exchange standard applies, which clients may exchange, how audience and scope are set, how long exchanged tokens last, and where the subject token comes from. Read each row as a decision point, and confirm the exact setting names in the Admin Console for your Keycloak version before you build.
| Option | What it controls | When it fits | Trade-off |
|---|---|---|---|
| Standard token exchange (RFC 8693) | Exchanges a subject token for a new token through the supported standard flow | Service-to-service delegation where the standard flow covers the pattern you need | Confirm feature status and enablement for your version before you design around it |
| Legacy token exchange | Older exchange behavior kept for patterns the standard flow does not cover | Only when a required pattern is missing from standard exchange and you have a retirement plan | Deprecated, so it adds upgrade and removal risk over the life of the system |
| Client permissions | Which clients may request an exchange, set on the target client's permissions | Named confidential clients that must act on behalf of users or other services | Broad permissions let any client mint tokens for other services, so review them regularly |
| Audience and scope settings | The audience the new token targets and the scopes it carries | One narrow audience per downstream API, so each token serves a single service | More audiences means more client and scope configuration to maintain and test |
| Token lifetimes for exchanged tokens | How long the newly issued token remains valid | Short lifetimes suit internal hops where the caller can exchange again when needed | Short lifetimes increase exchange calls and load on the Keycloak server |
| Same-realm subject token | The subject token is issued to users or clients of the same realm | Internal applications where all identities live in one realm | Simplest trust model, but external identities must be brokered into the realm first |
| Brokered identity provider subject token | The subject token originates from an upstream identity provider linked by brokering | Partner or workforce identities held in an external directory or identity provider | Requires consistent trust settings, claim mapping and token handling for each upstream provider |
How to set up token exchange in Keycloak
This sequence takes a service from a confirmed Keycloak version and exchange type to a tested token exchange, with an audience-scoped token that the target service validates. Each step ends with a check you can run before moving on.
Confirm the Keycloak version and exchange type
The platform owner checks the running Keycloak version against the upgrade notes and the server administration guide, then decides whether the design needs standard token exchange (RFC 8693) or the deprecated legacy exchange. Standard exchange should be the starting point for new work, and legacy should only be kept where an existing flow depends on it. Confirm whether the token exchange feature must be enabled for your version, and record the version, exchange type and feature state in the design document. The step is done when the platform owner has reviewed and approved that record.
Create the calling and target clients
The identity administrator creates one confidential client for the service that will perform the exchange, with client authentication turned on so it can authenticate to the token endpoint. The administrator then creates a client for the target API that will receive the exchanged token. Keep the calling client's secret in your secrets manager and out of realm exports. The check is that the calling client shows client authentication enabled, and both clients appear in the client list with distinct client IDs.
Configure audience and exchange permissions
The identity administrator lists which clients the calling service may exchange tokens for, and configures the audience so the issued token carries the target's client ID in the
audclaim. This is done with an audience protocol mapper or the client scope settings. Where your Keycloak version requires it, the administrator also grants the calling client permission to exchange toward the target through the target client's permission settings. Confirm the exact permission model in the documentation for your version. The check is that an exchange requesting an audience outside the approved list is refused.Define the subject token source
The team identifies where the subject token comes from: a user sign-in through an authorization code flow, or a service token obtained through the client credentials grant. The team confirms that the subject token is issued by this realm and that the calling client is permitted to present it. It also documents which claims carry the user identity and which identify the calling service. The check is that a sample subject token decodes with an
issvalue for this realm, asubvalue for the expected user or service account, and anazpvalue for the client that requested it.Test an exchange with a sample request
In a test realm or a non-production client, the developer sends a POST to the realm token endpoint with the grant type set to
urn:ietf:params:oauth:grant-type:token-exchange, the calling client's credentials, thesubject_tokenvalue, asubject_token_typethat matches the token, and anaudienceset to the target client ID. The check is a successful response containing an access token, token type and expiry. An error response points back to the client settings, permissions or audience mapper, so fix those before testing further. Keep the request and response in the runbook for later reference.Verify token claims at the target service
The developer decodes the exchanged token and confirms that
audcontains the target,azpidentifies the calling client,subreflects the expected user or service account, andexpis in the future. If your delegation pattern adds anactclaim, confirm that the target service reads it. The target service then validates the token signature using the realm's published keys and must reject the token when the audience is altered or does not match. The step is complete when the target accepts the valid token and rejects the altered one.
Security risks in token exchange and how to contain them
Token exchange lets one service trade a token for another, so a single exchange can widen who a token is valid for and what it can do. The cards below cover the risks that tend to follow from that, and the controls that contain each one. Treat them as a checklist for design review and for the audit evidence you will need later.
Over-broad exchange permissions
Token exchange is only as safe as the clients allowed to perform it. If a client can exchange tokens for any audience, a compromise of that one client becomes a path to every downstream service. Grant the exchange permission only to the specific clients that need it, for the specific target clients they call, and review those permissions whenever a new service is added. Confirm in your own realm which clients hold exchange permissions before go-live.
Keycloak docsConfused deputy delegation
A service that exchanges a user's token on the user's behalf can end up acting with its own authority instead of the user's. The downstream service then sees a request that looks legitimate but was not what the user asked for. Keep the subject of the exchanged token tied to the original user, and make each service decide what the request is allowed to do based on that subject. Test this with a scenario where the intermediate service receives a request it should refuse.
Tokens with wider audiences than intended
An exchanged token that lists several audiences, or that is accepted by a service it was never issued for, can be replayed against systems the user never intended to reach. Request a token for a single audience per target service, and have each service check that the audience claim names it before it trusts the token. Services that accept any valid token from the realm have no real boundary, so verify this behavior in each integration.
Short token lifetimes
An exchanged token that lives longer than the work it supports gives an attacker more time to use a leaked copy. Set the lifetime of exchanged tokens shorter than the lifetime of the user's login session, and keep the intermediate service from caching them longer than needed. Confirm the access token lifetime that applies to exchanged tokens in your realm and document it alongside the audience each token serves.
Leaked exchanged tokens
Exchanged tokens travel through more hops than a standard login, so each extra hop is another place a token can end up in logs, traces or error messages. Use TLS on every hop as the production guidance requires, keep tokens out of URLs and application logs, and make sure the admin console and Administration REST API sit on a separate hostname or context path from public frontend URLs. Check your reverse proxy and log pipeline, since they often capture headers by default.
Production guideExchange events in audit logs
Without a record of who exchanged which token for which audience, an incident involving delegated access is hard to reconstruct. Enable login and admin event logging in Keycloak, forward those events to your log platform, and define which exchange events must be retained and reviewed. Ask your auditors which evidence they expect for delegated access, and confirm that your logging design can produce it before the system goes live.
Operating token exchange after go-live
Token exchange needs its own monitoring, because a broken exchange often fails quietly. Applications that depend on a delegated token will usually report a generic authorization error, not the exchange that failed. Before go-live, decide who watches exchange traffic and how. If your Keycloak deployment runs with --metrics-enabled=true, Keycloak exposes Prometheus-format metrics at /metrics on the management interface, and the Keycloak observability guide describes the optional HTTP request histograms. Confirm in your own test environment which series change when you call the token endpoint with the exchange grant type, then build dashboards and alerts on the request rate and error ratio for that path. Set alert thresholds from your observed baseline in production, not from numbers copied from another deployment.
Admin event and audit trails cover the other half of operations. Exchange permissions are granted through client and permission configuration in the admin console, so every change to those settings should be traceable to a person or automation account. Confirm that admin events are enabled and retained for long enough to answer an investigation, and that they are forwarded to the log platform your security team already uses. Because exchange grants let one client act on behalf of another, review who holds the rights to change clients, scopes and permissions, and treat those roles as privileged in your access reviews.
Client permission drift is the most common operational failure after an upgrade. Check the upgrade notes for each Keycloak minor release, since the project states that breaking changes in a minor release are opt-in, and confirm which defaults changed for your version. Export your realm configuration before and after each upgrade and diff the clients, scopes and permissions that affect exchange. Then run a regression test for each exchange pattern you use, including the impersonation-free delegation path, the audience-restricted service path and any legacy exchange still in use, and record the expected token claims and rejected requests. Keep these tests in version control so they run as part of every upgrade rehearsal.
Questions buyers ask about token exchange work
What drives the cost of a Keycloak token exchange project?
The cost follows the number of exchange flows, the number of downstream services that accept the exchanged tokens, and how many of those flows still depend on the deprecated legacy token exchange. Each flow needs a client design, a permission model, an audience and scope decision, and tests. Fixed-scope work is priced from a written scope, so the quote should list each flow and each downstream service by name. DeployOpen does not publish a price list. Ask for the cost split between design, build, testing and handover, and whether any ongoing support is priced separately as a retainer.
How long does a token exchange design and build take?
Duration depends mainly on how many exchange flows exist and how many downstream services must trust the exchanged tokens. A single flow to one downstream API is a small piece of work. Several flows across multiple services need more time for design reviews, client and permission setup, and integration testing in each service. No fixed duration is stated here. Ask for a timeline in the written scope that ties each milestone to a flow or service, and confirm which dependencies, such as API owner reviews or test environment access, sit on the client side.
What does the client team need to provide for this work?
The work needs identity architects who can confirm the realm, client and trust model, API owners who can state the audience, scopes and claims each service expects, and a test environment that mirrors production Keycloak and downstream services. Security reviewers should approve the delegation rules before they reach production. Name these people in the scope and agree how quickly decisions will be made, because most delays come from unresolved audience and permission questions rather than from configuration work.
Can an internal team implement token exchange without outside help?
An internal team with Keycloak administration experience and access to the downstream API owners can build a single, simple exchange flow. The harder parts are deciding which flows are delegation, which need impersonation-like behavior, and how to keep the legacy version out of new designs. Teams new to RFC 8693 usually benefit from a design review before building. Whether to do it alone depends on the number of flows, the security review requirements and how much testing the team can run. Check the Keycloak documentation for the version you run before committing.
Which parts of token exchange still depend on the deprecated legacy version?
Standard token exchange under RFC 8693 is the supported path for new work, and the first design decision is to confirm that each flow fits it. Flows that rely on features only the legacy version offered need a documented plan: either a redesign onto the standard flow or a dated exception with an owner. Confirm the exact feature gaps against the Keycloak documentation for your release, because support status changes between releases. Record each legacy dependency in the design so it can be reviewed during upgrades.
How does a service-to-service delegation pattern work in Keycloak?
A calling service presents a token it already holds to Keycloak and asks for a new token scoped to a different downstream audience. Keycloak checks the client's permission to exchange, validates the subject token, and issues a token that identifies both the original user and the calling service where the design requires it. The downstream service then validates the audience and scopes before acting. Keep the exchanged token short-lived and limit which clients may request each audience. Verify the actor and subject claims in each downstream service during testing.
What should we verify before going live with token exchange?
Verify that each exchange flow returns tokens only for the intended audience and scopes, that unauthorized clients receive errors, and that downstream services reject tokens with the wrong audience. Test token lifetimes, revocation behavior and what happens when a user is disabled mid-session. Review logs for each exchange so the team can trace which client requested which token. Ask for these test cases as named deliverables in the written scope, along with a retest after any fix.
What recurring work follows a token exchange build?
After go-live, recurring work includes reviewing exchange permissions when services change, checking the Keycloak release notes before each upgrade, and retesting flows after changes to client settings or downstream APIs. Keycloak ships minor releases several times a year, so the team should plan regular upgrade testing. Ongoing support, upgrades and continuous testing can be arranged as a retainer, which is quoted separately from the initial fixed-scope build.
How DeployOpen scopes and delivers Keycloak token exchange
DeployOpen plans, implements, tests, documents and supports Keycloak token exchange inside the client's own infrastructure, so the delegation model is designed against the client's real services and trust boundaries. Engagements are fixed-scope, with scope, deliverables and timelines agreed in writing before work starts.
How we scope
- Inventory which services call each other and which need delegated or impersonated tokens, before any client is configured.
- Decide whether each flow fits standard token exchange or needs the deprecated legacy version, and record the reason.
- Agree in writing the realms, clients, audience values, token lifetimes and test cases covered by the fixed scope.
How we build
- Configure the token exchange permissions, client policies and audience restrictions so each exchange grants only the scopes the flow needs.
- Build the service-to-service delegation pattern in your environment, including service accounts and how the subject token is carried.
- Test each exchange path, including denied requests, expired subject tokens and attempts to widen scope or audience.
How we hand over
- Deliver a written configuration record covering clients, permissions, audiences and the reasoning behind each exchange path.
- Document the test cases, their results and the steps to rerun them after a Keycloak upgrade or configuration change.
- Walk your platform and security teams through the runbook so they can review and operate the exchange flows themselves.
How we support
- Support upgrades of Keycloak and review token exchange behavior against each release's upgrade notes before rollout.
- Continue testing exchange paths as new services join, with ongoing support and continuous testing available as a retainer.
- Keep the scope and deliverables aligned with your change process, so each new delegation flow gets reviewed before it goes live.

