Keycloak token exchange (RFC 8693)

Keycloak token exchange lets a service trade one token for another so it can call a downstream API on a user's behalf or on its own behalf. This page covers the supported standard flow, when the deprecated legacy version is still needed, and what to confirm before you build.

On this page

How Keycloak token exchange lets one service act for another

Keycloak token exchange lets a client present a token it already holds, the subject token, to the Keycloak token endpoint and receive a new token for a different audience or a narrower scope. The Keycloak server administration guide describes this as the RFC 8693 OAuth 2.0 Token Exchange grant. Consider a single-page app that holds an access token issued for its own frontend client. The orders API trusts only tokens whose audience is the orders API, so the frontend call fails. Copying the frontend token into the downstream request would work, but it would carry rights the orders API does not need. Token exchange gives the calling service a token issued for the downstream API instead.

Teams usually need token exchange for three patterns. Delegation applies when a service acts on behalf of a signed-in user, and the downstream service must see both the user and the calling service. Audience changes apply when the downstream API accepts only its own audience. Downscoping applies when the new token should carry fewer scopes than the original. Each pattern forces decisions. Decide whether the downstream token must record the original subject, which clients are allowed to perform the exchange, and which target audiences and scopes each caller may request. Write these decisions down before configuring anything, because they determine the client permissions you will review later.

A simpler design is often enough. If a service acts only on its own behalf, the client credentials grant gives it a token tied to its service account, with no user context. If the frontend can request the downstream audience in its own token through an audience mapper or a client scope, a second token request is unnecessary. Token exchange adds a token request on every hop, a permission you must maintain, and another point to audit. Ask whether the downstream API truly needs the user's identity, and whether the audience design could be fixed at the client instead. If neither question yields a clear need, choose the simpler design.

Token exchange features and their status depend on the Keycloak release you run. Before designing anything, read the server administration guide for your target version and confirm whether the standard token exchange feature is available and how it is enabled in that release. Confirm too that your intended pattern uses the standard RFC 8693 path rather than the legacy token exchange, which the project has deprecated. Do not rely on older blog posts or community examples for request parameters or permission names, since these change between releases. When you plan a version upgrade, check the upgrade notes for any change that affects your exchange flows, and test each exchange path in a non-production realm first.

Which Keycloak token exchange pattern fits your delegation case

This table compares four delegation patterns for Keycloak token exchange and one legacy case, showing where each fits, its main risk and what to confirm in the target release. Read each row against the trust relationship between your clients and downstream APIs. The main takeaway is that audience and scope narrowing, and limiting who may impersonate, matter as much as the pattern you choose.

PatternFitMain riskWhat to confirm in the target release
User-to-service exchangeA front-end or API exchanges the user's token for a token a downstream service accepts on the user's behalf.The downstream call inherits the user's full scope unless the exchanged token is narrowed.Which client policies, scopes and requested audiences the release allows for the exchange.
Service-to-service with a service accountA confidential client exchanges its own token for a downstream audience when no user is involved.Downstream services may not see which user triggered an action, so audit trails need deliberate design.Whether the service account roles are limited to the target audience and whether events record the calling client.
Audience narrowing for one downstream APIThe exchanged token is limited to a single resource audience with reduced scopes for one downstream API.Broad requested scopes or a missing audience check in the downstream API defeats the narrowing.How the release handles the audience parameter and whether the downstream API validates the aud claim.
Impersonation-style exchangeAn administrator or trusted service acts as another user, typically for support or testing scenarios.Actions appear as the impersonated user, and a compromised client can act for any account it may impersonate.Whether impersonation is enabled in the release, which clients may use it and where the events are recorded.
Legacy token exchange (deprecated)Only where a workload depends on a behavior the standard implementation does not cover.The deprecated feature may be removed in a later release, leaving the workload without a supported path.Whether the behavior still exists in the target release and what the upgrade notes say about it.

How Keycloak token exchange works step by step

Token exchange is a single request to the Keycloak token endpoint in which a calling client presents a token it already holds and asks for a different one. RFC 8693, OAuth 2.0 Token Exchange, defines the grant type and the parameters for this request, and Keycloak applies its own policy before it issues anything. The sequence below is illustrative: the calling client authenticates with its own client credentials, sends a subject token and identifies its type, names the token type it wants back and the audience that token is for, and then receives a new token only if Keycloak's permission checks allow the exchange. If any step fails, the request returns an error and no token is issued. Confirm the exact parameter names and accepted values against the documentation for your Keycloak version before writing client code.

Each of the three inputs changes the result in a different way. The subject token is checked first: Keycloak must recognize it as valid, unexpired and issued by a realm it trusts. The identity carried in that token becomes the basis for the new token, so a service that passes along a user's token also passes along that user's identity. The calling client identity decides whether the exchange is permitted at all. Keycloak needs to know which client is asking and whether that client has been granted the right to exchange tokens for the target, so a client that can sign in may still be refused. The requested audience sets which client the new token is meant for, and it is the input teams most often get wrong. A mismatch between the audience you request and the permissions you configured can produce a denial, so test each source and target pair explicitly.

The contents of the new token come from configuration as much as from the request. Keycloak builds claims from the client's settings, its client scopes and the protocol mappers attached to those scopes, including any audience mapper that places the requested audience into the aud claim. Scopes the calling client asks for are only useful if the target client and realm allow them, so the scope set in the result can be narrower than the subject token suggests. Treat this as a design decision: decide which claims each target needs, add only those mappers, and record which scopes each exchange pair may use. Then decode a token from a test realm and compare its claims with that design. The Keycloak server administration guide describes client scopes and mappers, but check the section for your version, because where exchange settings sit in the console can change between releases.

Two checks belong before any production traffic. First, confirm which token exchange variant your Keycloak version supports for your use case. The standard exchange described by RFC 8693 is the path to build on. Any feature that still depends on the legacy implementation should be listed as a dependency with an owner and a removal plan, because the legacy version is deprecated. Second, build a test matrix of calling client, subject token type, requested token type and target audience, and record the expected result for every row, including the denials. Re-run the matrix after each Keycloak upgrade and review the release notes for the version you move to. A matrix that covers denials is the cheapest way to find a permission that was granted too broadly.

What still needs the deprecated legacy token exchange

Start by finding every client, service and script that asks Keycloak to exchange a token. Legacy use often hides in service code, gateway policies and internal scripts that nobody has touched since they were written, so build the inventory from both the Keycloak side and the application side.

  • Keycloak logs and event data: Review token requests and client configurations in each realm over a period long enough to cover monthly and quarterly batch jobs.
  • Application code and configuration: Search repositories, deployment manifests and gateway policies for token exchange grant types and the parameters the legacy flow used.
  • Owner and purpose: For each caller, record the owning team, the source and target clients, and the business function it supports.
  • Infrequent callers: Ask teams about disaster recovery jobs, backup tooling and partner integrations, which often run rarely and rarely appear in logs.

Confirm the inventory with each owning team before starting gap analysis, because a caller missing from the list is usually the one that fails after cutover.

Setting up Keycloak token exchange in a realm

This sequence sets up RFC 8693 token exchange in one Keycloak realm, from enabling the feature to confirming that each permitted exchange succeeds and each disallowed one is refused. The result is a tested set of calling clients, target audiences and exchange permissions that can be reviewed and rebuilt from version-controlled configuration.

  1. Confirm the release and enable the feature

    Start in a non-production realm. Read the release notes and the server administration guide for the Keycloak version you run, because token exchange support and its enabling setting are version-specific and should be confirmed against that version's documentation. Enable the feature as those docs describe, restart the server, and confirm the setting is active in the server logs and the realm configuration. Your platform team or DeployOpen's engineers can carry this out. Done when the feature is confirmed on the target version in a test environment.

  2. Define calling clients and their authentication

    List every service that will request an exchanged token and create a client for each one, with the authentication method it will use, such as a client secret, signed JWT or mutual TLS where the target version supports it. Confidential clients with service accounts fit most backend callers. Record each caller's purpose and owner alongside its client ID. Check by requesting a token from each client with its real credentials, confirming the server accepts the method, and confirming a wrong secret is rejected.

  3. Create target audiences and client scopes

    Create a client for each downstream API that should receive an exchanged token. Build client scopes that add its identifier to the audience claim through an audience mapper, and include only the scopes that API needs. Assign those scopes to the calling clients where the exchange is permitted. Check by exchanging a test subject token for the target and decoding the result to confirm the aud claim names the target client and the scope claim lists only the intended scopes.

  4. Configure exchange permissions for each caller

    On each target client, open the token exchange permission settings and enable fine-grained permissions. Create a client policy that names the calling client, then bind that policy to a permission that allows the exchange. Restrict each policy to the one caller and target that need it, and avoid policies that match every client. Check that the permitted caller receives an exchanged token and that the permission and policy names match your written exchange matrix.

  5. Test with representative subject tokens

    Obtain subject tokens the way production clients will, using a user login and a service account token, and cover each token type your callers will present. Run the exchange and decode the output to verify the subject, the authorized party and any actor claims the target version emits. Confirm the expiry and scopes are no broader than the subject token allows. Check that each token type yields the expected claims, recorded in a test log that another engineer can repeat.

  6. Run negative tests for refused exchanges

    Attempt the exchanges that must fail: a caller without a permission, an unlisted audience, a client using the wrong authentication method, and an expired or altered subject token. Record the error response for each and confirm the server event log shows the refusal. Keep these tests in the same suite as the positive tests so every change reruns both. Check that every disallowed request returns a refusal and that each negative case is tied to a specific permission it exercises.

  7. Record permissions as configuration as code

    Export the realm configuration, including the clients, client scopes, policies and permissions, and store it in version control with a review step for every change. Reapply the export to a clean non-production realm, then promote the same reviewed change to production through your normal release process. Run the positive and negative test suite at each promotion. Check that a fresh import reproduces the test results and that the repository matches what runs in production.

Security risks in delegation and how to contain them

Token exchange lets one service obtain a token for another audience on behalf of a user or client, which widens what a single credential can reach. The cards below pair each risk with the containment control to configure and check in your Keycloak realm and in the proxy that fronts it.

Over-broad token audiences

An exchanged token that names several services can be presented to any of them, so one exchange may open more resources than the caller intended. Keep each exchange targeting a single downstream resource server, and restrict which clients may request that audience. Keep token lifetimes short so a leaked exchanged token loses value quickly. Check the configured audience and lifetime for every exchange path before release, and confirm the lifetime values against your own risk assessment because the right settings depend on each downstream call.

Tokens carrying excess scope

An exchange can carry more scopes or roles from the subject token into the new token than the downstream call needs. Use explicit permissions so each exchange requests only the scopes its target uses. Review the client scopes and role mappings attached to every exchange client in Keycloak Realm settings, and test that the exchanged token contains nothing beyond what the downstream service checks. Repeat this review whenever a downstream service adds a new endpoint.

Confused-deputy calls

A service with its own privileges can act for a user it should not represent, because the exchange trusts the calling client more than the subject it acts for. Limit which clients may perform token exchange and for which users, groups or audiences, and document each delegation pattern in writing. Test negative cases, such as a user outside the intended group, and confirm that Keycloak refuses the exchange before the pattern goes live.

Missing audit trails for exchanges

Without records, teams cannot reconstruct which client exchanged which token, for which user, and when. Enable login and admin event logging for the realm and confirm how long events are stored. Forward events to your log platform or SIEM through the Listener SPI. Confirm with your Keycloak version whether each token exchange itself appears as an event, because the documented event settings are the starting point and may need supplementing with downstream service logs.

Unencrypted calls and admin exposure

Exchange requests carry client credentials and tokens, and a publicly reachable admin console or Administration REST API widens the attack surface of the same server. Apply TLS to all communication that Keycloak participates in, and confirm the setting for each internal hop in your design. Place a reverse proxy in front of Keycloak that restricts paths, and serve the admin console and Administration REST API on a separate hostname or context path from public frontend URLs, as Keycloak's production guidance describes.

How clustering, upgrades and metrics affect token exchange in production

Token exchange runs at the token endpoint, so its availability follows the availability of the Keycloak cluster that serves that endpoint. Keycloak documents three high availability architectures. Two are supported designs: a single cluster, optionally spread across availability zones, and multi-cluster deployments (v2) that do not need an external Infinispan cluster. The deprecated multi-cluster v1 design should not be chosen for new work. Both supported designs require a synchronously replicated database, because the nodes need a consistent view of sessions and client data to handle exchange requests reliably. Confirm with your database team that replication is synchronous across every zone or site in your plan. Also confirm how the clients calling the exchange behave during a node or database failover, since they may need to retry a request that was in flight.

Upgrades are where clustering and release planning meet. If you run the Keycloak Operator, its documentation strongly recommends manual approval mode for operator updates, which keeps a new version from rolling out before someone reviews it. Pair that setting with a staging environment that uses the same database engine, realm configuration and exchange clients as production. Database schema migration is the second decision. Keycloak migrates the schema automatically at startup by default. The upgrading guide also describes manual migration, where administrators apply the SQL themselves, and suggests it for large deployments. Automatic migration keeps rollouts simple but ties schema changes to pod startup. Manual migration gives your database administrator a reviewable script and a clear rollback point, at the cost of more steps per release. Choose a path before the first production upgrade and record it in the release runbook.

Keycloak plans four minor releases a year and says breaking changes in a minor release will be opt-in. That makes each minor release the unit of your token exchange regression test. After every minor release, run the exchange flows your services depend on in staging. Cover the subject token types you accept, the audiences and scopes you request, the clients allowed to perform exchange, and the error responses your services handle. Then read the release notes for opt-in changes and decide deliberately whether to enable each one. The 26.8 upgrade notes show why this matters beyond exchange. They include mandatory signature validation of backchannel logout tokens from external providers and enforced SMTP StartTLS, either of which can break integrations that look unrelated to token exchange. Keep a dated record of each decision so an auditor or on-call engineer can see why a setting changed.

Metrics show whether exchange is healthy between releases. When Keycloak starts with --metrics-enabled=true, it exposes Prometheus-format metrics at /metrics on its management interface. Optional HTTP request and cache histograms add latency and cache visibility. Scrape the management interface only from your monitoring network, and confirm that your reverse proxy never routes it to the public frontend. The production guide asks for path restrictions and separate hostnames for administrative endpoints, and the same care applies here. Build dashboards and alerts for token endpoint request rates, error rates and latency, and cache behavior after node restarts and failovers. Compare these signals before and after each upgrade in staging. Confirm the exact metric names in the version you deploy against the observability guide, because alert rules should be written against the names your running release actually exposes.

What to confirm before you design around token exchange

Token exchange in Keycloak depends on which parameters, endpoints and client settings your release actually supports, so these checks belong before any architecture is drawn. Each card names one item to verify, where to check it, and what a gap would change in your design.

Exchange type and parameters

Standard token exchange in Keycloak covers specific grant types, subject and actor token types, and request parameters such as audience and requested token type. Confirm that the exact combination your design needs appears in the documentation for the release you will run. A general reading of RFC 8693 does not establish that support. Check the server administration guide for that release and note any preview or feature flag that applies to the flow.

Legacy endpoint dependencies

Keycloak's legacy token exchange is deprecated, and older integrations may still call it. Inventory every client, API gateway and service account that sends an exchange request to the token endpoint, and record which request format each one uses. Any caller that depends on legacy behavior changes the migration scope and needs its own test plan before you commit to the standard flow.

Audience validation at resource servers

An exchanged token is only as safe as the checks applied to it downstream. Each resource server in the delegation chain must validate the issuer, signature and audience claim, and reject tokens minted for another service. Confirm how each API reads the aud claim, whether its libraries accept multiple audiences by default, and how a token issued for one service is kept from being replayed against another.

Client authentication methods

The client that requests an exchange must authenticate to the token endpoint. List the methods your callers can use, such as client secret, signed JWT or mutual TLS, and confirm which of them your release and client configuration accept for exchange requests. A caller that cannot use a supported method will force changes to its code, its secret handling or your client policies, so record this before you choose a delegation pattern.

Red Hat build subscription scope

Red Hat build of Keycloak is Red Hat's supported distribution based on the open source project and replaces Red Hat Single Sign-On. Before you rely on a feature, check the Red Hat product page and its documentation to see whether the supported feature set and support terms match the upstream release you tested. Ask Red Hat in writing whether token exchange behavior differs under your subscription.

What buyers ask before they build Keycloak token exchange

What drives the cost of building Keycloak token exchange?

The number of exchange paths, audience design, legacy migration, testing, and high availability and upgrade scope drive most of the effort.

Exchange paths: each path is a separate trust decision about which client may trade which token, for which downstream audience, and with which scopes. Audience design: this sets how many resource servers must accept the exchanged token and how much configuration sits in clients versus scopes. Legacy migration: existing applications that depend on the deprecated version each need a replacement and a cutover plan. Testing: every path and audience combination needs positive and negative cases. HA and upgrades: designs that must survive node failure and future Keycloak releases add build and verification work.

Ask for each path and audience to be listed in the written scope, so the estimate follows from that list.

How long does a scoped Keycloak token exchange engagement take?

Duration follows the same drivers as cost, so no timeline is fixed until those inputs are written down. The main inputs are the number of exchange paths, how many audiences and resource servers must accept exchanged tokens, whether legacy token exchange must be replaced, how much of a test environment is available, and whether high availability is in scope. A small set of well-defined paths with a ready test environment is simpler to schedule than a broad migration across many services.

Ask the proposal to show phases: design and decisions, build in a non-production environment, verification, cutover, and handover. Each phase should state its entry and exit criteria and the people who must be available. Treat any single duration as provisional until the scope document lists the paths, audiences, and test cases it covers.

What does a token exchange project need from our team?

A token exchange project needs three things from your side: decision-makers, application knowledge, and a place to test.

Identity architects own the realm, client, and audience model, and they sign off on which clients may exchange which tokens. Application owners confirm which services call which, what token contents they expect, and they run acceptance tests for their own services. A test environment should be a non-production Keycloak deployment that matches production's database and clustering layout, with test clients and test identities.

You also need access to change windows for cutover and a named owner for exchange decisions after handover. Without these, design questions stall and tests run against setups that do not match production.

Can an internal team build Keycloak token exchange without an outside partner?

Yes, a team with solid OAuth 2.0 and OpenID Connect knowledge, Keycloak administration experience, and time to read RFC 8693 and the Keycloak documentation can build it. Risk tends to concentrate in four places: token and claim design, Keycloak client permissions and scopes, database and high availability operations, and automated testing of token flows.

The gaps that matter most usually appear as exchange permissions that are broader than the use case needs, or as legacy dependencies that were never inventoried. If your team has not run Keycloak in production or has no test environment, an outside partner can shorten the design phase and add an independent review. Either way, internal ownership must exist after handover, so define which parts your team will operate and maintain before the build starts.

What should a written quote for token exchange include?

A usable quote lists what will be built and what will not. DeployOpen works on fixed scope agreed in writing before work starts, and the quote follows from that written scope. It should include:

  • Exchange paths: each source client, target audience, scope set, and token type.
  • Legacy components: which deprecated uses are in scope and how each is replaced.
  • Environments: the Keycloak topology, database, and high availability design being built.
  • Testing: test cases per path, negative cases, and who runs them.
  • Upgrades: the target Keycloak version and how later upgrades are handled.
  • Documentation and handover: runbooks, configuration records, and knowledge transfer.
  • Exclusions and assumptions: for example, changes to downstream application code and assumptions about your network.
  • Change handling: how later requests are priced and approved, and whether post-handover support is a separate retainer.
Why does audience design change the effort for Keycloak token exchange?

Audience design decides which services can accept an exchanged token, so it sets the size of the trust model. A narrow audience per resource server keeps each exchanged token limited to the service it was issued for. A broad audience lets one token travel further, which reduces the number of exchanges but widens what a leaked token can reach.

Each audience needs a clear mapping from client, scope, and user context to the claims the target service expects. Downstream services must validate the audience claim, and that validation is a change in their code or configuration. Ask the architects to document the audience for every exchange path, and ask application owners to confirm their validation logic before cutover.

What usually goes wrong after Keycloak token exchange goes live?

The most common problems are permissions that are broader than intended, audiences that downstream services do not check, and token contents that drift from what consumers expect.

Over-broad exchange permissions: clients gain the ability to exchange tokens they never needed to trade. Unchecked audiences: a service accepts an exchanged token that was issued for another service. Missing visibility: no one notices a new or changed path until an incident.

Review exchange permissions on a fixed schedule and after every change. Enable metrics with the metrics option so Prometheus-format data is served at the metrics path on the management interface, and alert on unexpected patterns. Keep a test suite that runs each exchange path after every configuration change.

How DeployOpen scopes and delivers Keycloak token exchange

DeployOpen plans, builds and documents Keycloak token exchange (RFC 8693) inside infrastructure you control, starting from a written scope. We confirm which exchange type your clients need, which parts depend on the deprecated legacy feature, and how delegated tokens will be issued and audited before any configuration changes are made.

How we scope

  • The written scope names each exchange flow, its calling clients and the target audiences.
  • We confirm which parts of the work use standard token exchange and which still depend on the deprecated legacy version.
  • Engagements are fixed-scope, with the written scope agreed before work starts and ongoing support available as a retainer.

How we build

  • Clients, audiences and permissions for each exchange are configured and recorded so each rule can be reviewed.
  • Token lifetimes, requested scopes and delegation chains are tested with positive and negative cases before go-live.
  • Where a flow depends on legacy token exchange, we document the dependency and the planned move away from it.

How we hand over

  • Handover includes configuration records, the exchange flow diagram, test cases and the rule for each client and audience.
  • Your team receives runbooks for rotating signing keys, adding a new exchange client and investigating a rejected exchange.
  • Test results and open questions are recorded, so your security and compliance reviewers can trace each delegated token.

How we support

  • Ongoing support is available as a retainer for changes to exchange rules, client onboarding and release reviews.
  • Keycloak upgrades are planned against the release notes, because exchange behavior can change between versions.
  • Teams that need continuous checks can add security testing of the exchange endpoints under a retainer.

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.