How to Implement a Token Exchange with OAuth
Exchange tokens between services with the RFC 8693 token exchange grant so a service acts on behalf of a user without a shared long-lived credential.
On this page
Introduction
In a microservice architecture, a request enters through a gateway with a user’s token and then fans out to internal services. Passing the user’s original token everywhere is risky: it may carry more scope than an internal service needs, and a leak exposes the user’s full authority. Exchanging it for a narrower, audience-specific token limits the blast radius. RFC 8693 (OAuth 2.0 Token Exchange) is the standard for this: a service presents a token and asks the authorization server for a different token that represents the same subject with narrower scope or a different audience.
Why Exchange Instead of Forward
Forwarding the user’s token to every internal service means every service can call every API the user can, and a compromise of any service yields the user’s full token. It also breaks least privilege: a service that only reads a profile still holds a token that can spend money, because the token was minted for the user’s whole session.
Token exchange mints a token scoped to exactly what the calling service needs to do. The subject stays the user, so audit logs still attribute the action to the user, but the audience and scope are the internal service’s. A leaked exchanged token grants far less, and it is short-lived.
# forwarding vs exchange
forward: user_token(aud=api, scope="read write pay") -> service A -> service B
=> every service holds the user's full token
exchange: user_token -> AS -> svcA_token(aud=serviceB, scope="read")
=> service B only sees a narrow token, subject still the user
The Token Exchange Grant
Exchange uses the token endpoint with grant_type urn:ietf:params:oauth:grant-type:token-exchange, along with the subject_token and its type, the requested token type, and optionally the audience, scope and actor token. The authorization server validates the subject token and returns a new token whose subject is derived from it.
The exchanged token is typically a JWT with a sub claim of the user, an aud claim of the target service, narrowed scopes, and often an act claim naming the acting service. The act claim is what preserves the delegation chain: the target service can see both that the user is the subject and that a specific service is acting on their behalf.
POST /oauth/token HTTP/1.1
Host: auth.example.com
Content-Type: application/x-www-form-urlencoded
grant_type=urn:ietf:params:oauth:grant-type:token-exchange
&subject_token=<user access token>
&subject_token_type=urn:ietf:params:oauth:token-type:access_token
&requested_token_type=urn:ietf:params:oauth:token-type:access_token
&audience=https://orders.internal
&scope=orders:read
Requesting the Right Scope and Audience
Ask for the narrowest scope the calling service needs for the specific call, not the union of what it might do. If service A is calling service B to read an order and then display it, request orders:read, not orders:readwrite. Narrow scope is the entire benefit of exchanging, so a blanket request wastes it.
Set the audience to the target service, so the exchanged token cannot be replayed against a different service. The target service must verify both the audience and the issuer, and reject a token minted for another audience. Audience binding is what limits a leaked token to one service.
export async function exchangeForService(userToken: string, audience: string, scope: string) {
const res = await fetch(TOKEN_ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',
subject_token: userToken,
subject_token_type: 'urn:ietf:params:oauth:token-type:access_token',
requested_token_type: 'urn:ietf:params:oauth:token-type:access_token',
audience,
scope,
}),
});
if (!res.ok) throw new Error('exchange_failed: ' + res.status);
return res.json() as Promise<{ access_token: string; expires_in: number }>;
}
Delegation and the Actor Chain
When service A exchanges and then calls service B, B may itself exchange again to call service C. Each step should add an actor, building a chain from the user to each acting service. The act claim can nest, so the final service can see the full delegation path and attribute the action correctly in its logs and policy.
The chain also lets policy be precise: a service can accept a token only when the acting service is one it trusts for that operation, and refuse a token whose actor chain includes an unknown or over-scoped service. Preserving the chain is what keeps least privilege intact across multiple hops.
{
"sub": "user_123",
"aud": "https://orders.internal",
"scope": "orders:read",
"act": {
"sub": "service-a",
"act": { "sub": "gateway" }
},
"iss": "https://auth.example.com",
"exp": 1698249740
}
// sub = the user (still accountable); act = who is acting, nested per hop
Verifying Exchanged Tokens at the Target
The target service verifies the signature against the issuer’s JWKS, the issuer, the audience, the expiry and the scope. It then authorises the request against the sub (the user) and the act chain (the acting services), rather than against the token alone. Verification without an audience check is the classic mistake that lets a token for one service be used on another.
Because the token is short-lived and narrow, verification can be entirely local: no introspection call is needed if the token is a self-contained JWT. Keep the lifetime short so revocation is less critical, and if a service must revoke immediately, add a denylist keyed on the token id or use a short-lived token plus introspection for high-risk operations.
async function verifyExchanged(token: string, expectedAudience: string) {
const { payload } = await jwtVerify(token, jwks, {
issuer: 'https://auth.example.com',
audience: expectedAudience, // reject tokens for other services
});
if (!payload.sub) throw new Error('no_subject');
// authorise against sub (user) + act chain (acting services), not the token
return { user: payload.sub as string, actor: (payload.act as { sub?: string })?.sub };
}
Caching and Failure Handling
Exchanging on every call adds a round trip to the authorization server. Cache the exchanged token for its lifetime, keyed by the subject token id, the audience and the scope, so repeated calls reuse one exchange. Cache only until shortly before expiry, and never cache across audiences, because the token is audience-bound.
If the authorization server is unavailable, the call cannot be exchanged and the request should fail rather than falling back to forwarding the user’s token, which would silently lose the least-privilege property. For high-availability paths, consider a local exchange capability or a cached token with a small safety margin, and alert on exchange failures as an availability signal.
const cache = new Map<string, { token: string; exp: number }>();
async function exchangeCached(userToken: string, audience: string, scope: string) {
const key = `${audience}|${scope}|${hash(userToken)}`;
const hit = cache.get(key);
if (hit && hit.exp > Date.now() + 5_000) return hit.token; // 5s safety margin
const { access_token, expires_in } = await exchangeForService(userToken, audience, scope);
cache.set(key, { token: access_token, exp: Date.now() + expires_in * 1000 });
return access_token;
}
Common Pitfalls and Conclusion
Do not forward the user’s full token to internal services when an exchange gives you a narrower one. Do not request broad scope “just in case”. Do not skip the audience check at the target. Do not cache an exchanged token across audiences. And do not fall back to forwarding when the exchange fails, which quietly removes the protection.
Token exchange lets a service act for a user without holding the user’s full authority. Request the narrowest scope and the exact audience, preserve the actor chain for accountability, verify issuer, audience and scope locally, cache within the token’s lifetime, and fail closed if the exchange is unavailable. Done well, a compromised internal service holds only the narrow tokens it was issued, not the user’s whole session.
Sources: RFC 8693: OAuth 2.0 Token Exchange, OAuth 2.0 Security Best Current Practice, RFC 9068: JWT Profile for OAuth 2.0 Access Tokens.
FAQ
- What is the difference between the subject and the actor?
- The subject is the user the token represents, so the action stays attributable to them. The actor is the service acting on the user's behalf. The act claim records the actor, optionally nested, preserving the delegation chain across hops.
- Should I cache exchanged tokens?
- Yes, for their lifetime and keyed by subject token, audience and scope, so repeated calls reuse one exchange. Never cache across audiences, because the token is audience-bound, and leave a small safety margin before expiry.
Report a problem with this articleOpens a pre-filled issue on GitHub.