Keycloak token exchange (RFC 8693)

Keycloak token exchange lets a client trade one token for another, for example to delegate a user's identity to a backend service. This page explains what the standard covers, where the deprecated legacy version still applies, and how to plan the design.

On this page

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.

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.

OptionWhat it controlsWhen it fitsTrade-off
Standard token exchange (RFC 8693)Exchanges a subject token for a new token through the supported standard flowService-to-service delegation where the standard flow covers the pattern you needConfirm feature status and enablement for your version before you design around it
Legacy token exchangeOlder exchange behavior kept for patterns the standard flow does not coverOnly when a required pattern is missing from standard exchange and you have a retirement planDeprecated, so it adds upgrade and removal risk over the life of the system
Client permissionsWhich clients may request an exchange, set on the target client's permissionsNamed confidential clients that must act on behalf of users or other servicesBroad permissions let any client mint tokens for other services, so review them regularly
Audience and scope settingsThe audience the new token targets and the scopes it carriesOne narrow audience per downstream API, so each token serves a single serviceMore audiences means more client and scope configuration to maintain and test
Token lifetimes for exchanged tokensHow long the newly issued token remains validShort lifetimes suit internal hops where the caller can exchange again when neededShort lifetimes increase exchange calls and load on the Keycloak server
Same-realm subject tokenThe subject token is issued to users or clients of the same realmInternal applications where all identities live in one realmSimplest trust model, but external identities must be brokered into the realm first
Brokered identity provider subject tokenThe subject token originates from an upstream identity provider linked by brokeringPartner or workforce identities held in an external directory or identity providerRequires 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.

  1. 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.

  2. 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.

  3. 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 aud claim. 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.

  4. 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 iss value for this realm, a sub value for the expected user or service account, and an azp value for the client that requested it.

  5. 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, the subject_token value, a subject_token_type that matches the token, and an audience set 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.

  6. Verify token claims at the target service

    The developer decodes the exchanged token and confirms that aud contains the target, azp identifies the calling client, sub reflects the expected user or service account, and exp is in the future. If your delegation pattern adds an act claim, 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 docs

Confused 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 guide

Exchange 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.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.