OAuth 2.0 Token Exchange (RFC 8693) in ASP.NET Core
Introduction
A service receives a token from its caller and now has to call a downstream API for the same user. Forwarding the token it received is wrong: the downstream API would accept a token that was never issued for it, and every audience check on the way would mean nothing. With OAuth 2.0 token exchange (RFC 8693), the service hands the token to the authorization server and gets back a new access token, issued for the API it is about to call, naming the same user, with a scope no wider than the token it started from. Microsoft Entra calls the same pattern the on-behalf-of flow, although its request uses other parameters.
The same grant serves a broker that turns a user's token into one for a backend, an MCP server calling upstream APIs (see Secure an MCP Server), and delegation, where the new token also records who acts for the user.
This guide follows one case: an orders API receives the user's token and calls an inventory API.
Turn the grant on
The token endpoint does not serve token exchange until the host registers it. Call AddTokenExchangeGrant before AddOidcServices or AddOidcCore, because they compose the grant handlers registered so far:
builder.Services.AddTokenExchangeGrant();
builder.Services.AddOidcServices(options => { /* tenants, clients, keys */ });Once registered, the discovery document lists urn:ietf:params:oauth:grant-type:token-exchange in grant_types_supported. A host that does not call AddTokenExchangeGrant neither serves the grant nor advertises it.
Declare both APIs as resources
The token the orders API receives and the token it exchanges it for are both addressed to resources the tenant declares, each with the scopes it accepts:
Resources =
[
new ResourceDefinition(new Uri("https://orders.example.com", UriKind.Absolute), new ScopeDefinition("orders.read")),
new ResourceDefinition(new Uri("https://inventory.example.com", UriKind.Absolute), new ScopeDefinition("inventory.read")),
],An exchange for a resource the tenant does not declare is refused with invalid_target. Machine-to-Machine Access shows where Resources sits in the tenant definition.
Allow a client to exchange tokens
The client that exchanges tokens is the orders API itself, registered as a confidential client: it authenticates at the token endpoint like any other. It needs the grant type in AllowedGrantTypes, and a few settings that limit what it may exchange:
{
"ClientId": "orders_api",
"ClientSecrets": [ { "Sha512Hash": "<base64 SHA-512 hash of the secret>" } ],
"AllowedGrantTypes": [ "urn:ietf:params:oauth:grant-type:token-exchange" ],
"AllowedScopes": [ "inventory.read" ],
"TokenExchangeAllowedSubjectTokenTypes": [ "urn:ietf:params:oauth:token-type:access_token" ],
"TokenExchangeAllowedAudiences": [ "https://inventory.example.com" ],
"CrossClientSubjectTokenExchange": "AddressedToClient",
"ResourceLocations": [ "https://orders.example.com" ]
}What each setting controls:
TokenExchangeAllowedSubjectTokenTypeslists the token types the client may present, assubject_token_typeand asactor_token_type. Left out, the client may present any type the server reads, ID tokens included, which state no scope and so set no bound on the scope of the new token. An empty list stops the client from using the grant at all.TokenExchangeAllowedAudienceslists the targets the client may exchange for, named asaudienceor asresource. Set it even for a client that names its target only asresource: without it, the client may exchange for any resource the tenant declares. It is explained in Choose the target.CrossClientSubjectTokenExchangedecides whether the client may present a token that was issued to another client. It is explained in Whose tokens a client may exchange.ResourceLocationsnames the addresses at which this client is itself a resource server. It matters forAddressedToClient.AllowedScopesbounds the scope of the tokens the client gets, as for any other grant.
A dynamically registered client declares the token types and audiences in its metadata as token_exchange_subject_token_types and token_exchange_audiences. The host lists the token exchange grant in NewClientOptions.AllowedGrantTypes, or a registration asking for it is refused with invalid_client_metadata.
NewClientOptions.TokenExchangeAudiences is both the default and the ceiling for audiences: a registration that omits token_exchange_audiences is given the whole list, and one that sends it may name only values from the list. With the option unset, a registration naming any audience is refused.
Which tokens can be exchanged
The server reads these token types, as the subject token and as the actor token alike:
urn:ietf:params:oauth:token-type:access_token: an access token this server issued, typedat+jwt.urn:ietf:params:oauth:token-type:id_token: an ID token this server issued.urn:ietf:params:oauth:token-type:jwt: either of the above, or an untyped JWT this server signed.urn:ietf:params:oauth:token-type:refresh_token: a refresh token this server issued and still honors.
A JWT is checked for its signature against the server's own keys, its lifetime, whether it or its session was revoked, and its sub, sid and auth_time claims: the exchanged token belongs to the session the subject token names and states the same sign-in, so a token without them is refused. A refresh token must refer to a grant the server still holds, in a session that has not been revoked, of a client that is allowed offline access; a public client's refresh token is exchanged only when it is bound to a DPoP key. A token naming a client the server no longer knows is refused.
To accept another kind of token, such as an assertion from a federated issuer, register an ISubjectTokenResolver under the token type URI after AddTokenExchangeGrant (see the extension points map). The grant finds it by that key and uses it for both subject and actor tokens.
Call a downstream API on behalf of the user
The client posts to the token endpoint and authenticates as usual. The token it received goes in subject_token, with its type:
curl -X POST https://auth.example.com/connect/token \
-u orders_api:$CLIENT_SECRET \
-d grant_type=urn:ietf:params:oauth:grant-type:token-exchange \
-d subject_token=$TOKEN_FROM_CALLER \
-d subject_token_type=urn:ietf:params:oauth:token-type:access_token \
-d resource=https://inventory.example.com \
-d scope=inventory.readAn exchange narrows and never adds, so inventory.read must already be in the token the orders API received. An access token carries only the scopes of the resources it is addressed to, so the front end asks for both resources when the user signs in, resource=https://orders.example.com and resource=https://inventory.example.com, with orders.read inventory.read as the scope. The user consents to the downstream access at that moment, and the orders API can pass on nothing the user did not grant.
The optional parameters:
resource(RFC 8707) oraudiencenames the API the new token is for.scopenarrows what the new token carries.actor_tokenwithactor_token_typeidentifies a party acting for the user, for delegation. One without the other is refused.requested_token_typemay be left out. The grant issues an access token, and any other value is refused.
The response carries the new token and its type:
{
"access_token": "<the issued access token>",
"issued_token_type": "urn:ietf:params:oauth:token-type:access_token",
"token_type": "Bearer",
"expires_in": 600
}An exchange never returns a refresh token or an ID token, even when the subject token's scope includes offline_access or openid.
Proof of possession carries over only for a client's own token. When the subject token is bound to a DPoP key and the client presenting it is the one it was issued to, the request carries a DPoP proof for that key, and the new token is bound to it too (token_type is then DPoP). A subject token bound to a client certificate works the same way: the client presents that certificate over mutual TLS, and the new token is bound to it.
A client exchanging another client's token cannot prove that client's key, so the subject token's binding is not carried over. To keep the downstream token sender-constrained, the client sends a DPoP proof of its own key with the request, and the new token is bound to that key.
From the calling service
Here is the same exchange made by the orders API in C#. The API keeps the token it received, SaveToken in its bearer options, so it can read it back:
builder.Services.AddAuthentication().AddJwtBearer(options =>
{
options.Authority = "https://auth.example.com";
options.Audience = "https://orders.example.com";
options.SaveToken = true;
});A typed HttpClient makes the exchange. Its base address is the authorization server and it authenticates the client with HTTP Basic, the default client_secret_basic method; the secret comes from a secret store, never from appsettings.json:
builder.Services.AddMemoryCache();
builder.Services.AddHttpClient<InventoryTokens>(client =>
{
client.BaseAddress = new Uri("https://auth.example.com/");
var credentials = $"orders_api:{builder.Configuration["Auth:ClientSecret"]}";
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials)));
});The class caches the new token under the token it was exchanged from, so each request from the same caller does not cost another round trip, and lets the entry expire before the token does:
public sealed class InventoryTokens(HttpClient http, IMemoryCache cache)
{
public async Task<string> ExchangeAsync(string subjectToken, CancellationToken cancellationToken)
{
var token = await cache.GetOrCreateAsync($"inventory:{subjectToken}", async entry =>
{
using var response = await http.PostAsync("connect/token", new FormUrlEncodedContent(new Dictionary<string, string>
{
["grant_type"] = "urn:ietf:params:oauth:grant-type:token-exchange",
["subject_token"] = subjectToken,
["subject_token_type"] = "urn:ietf:params:oauth:token-type:access_token",
["resource"] = "https://inventory.example.com",
["scope"] = "inventory.read",
}), cancellationToken);
response.EnsureSuccessStatusCode();
var issued = await response.Content.ReadFromJsonAsync<IssuedToken>(cancellationToken);
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(issued!.ExpiresIn * 0.9);
return issued.AccessToken;
});
return token!;
}
private sealed record IssuedToken(
[property: JsonPropertyName("access_token")] string AccessToken,
[property: JsonPropertyName("expires_in")] int ExpiresIn);
}An endpoint reads the token it received and calls the inventory API with the exchanged one:
app.MapGet("/orders/{id}/stock", async (string id, HttpContext context, InventoryTokens tokens,
IHttpClientFactory clients, CancellationToken cancellationToken) =>
{
var received = await context.GetTokenAsync("access_token");
var exchanged = await tokens.ExchangeAsync(received!, cancellationToken);
var inventory = clients.CreateClient();
inventory.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", exchanged);
return await inventory.GetStringAsync($"https://inventory.example.com/stock/{id}", cancellationToken);
}).RequireAuthorization();The inventory API validates the new token as any API does, with its own address as the audience:
builder.Services.AddAuthentication().AddJwtBearer(options =>
{
options.Authority = "https://auth.example.com";
options.Audience = "https://inventory.example.com";
});The token's client_id names the orders API, the client that exchanged it, and an API that has to know who acts for the user reads the act claim described below.
What the issued token carries
subis the subject token's subject, the user the exchange acts for, andclient_idis the client that made the exchange.audnames theresourceandaudiencevalues of the request. With neither, the server picks the target as at other grants: the resource whose scope was requested, then the tenant'sDefaultResourceIndicatorwhen one is set, and the issuer otherwise. Name the target explicitly, since a token addressed to the issuer is accepted by the server's own endpoints.scopeis never wider than the subject token's. A requested scope keeps only the values the subject token holds; the others are silently dropped, and a request that loses all of them is refused withinvalid_scope. With no scope requested, the new token takes the subject token's scope, filtered to the client'sAllowedScopes. Either way, it then keeps only the scopes the target resource declares, so a token for the inventory API carries no orders scopes. A subject token with noscopeclaim, such as an ID token, sets no bound of its own: the exchange is then limited by the client'sAllowedScopesalone, which is why the example lists onlyaccess_tokenamong the token types.authorization_details(RFC 9396) is carried over from the subject token. Each type must be one the requesting client'sAuthorizationDetailsTypesadmits: unset admits any type, and an empty list refuses a subject token that carries any.actrecords delegation, as described in Impersonation and delegation.
The new token stays tied to the subject token. It belongs to the subject token's session and keeps its auth_time, acr and amr, so it does not pass as a new sign-in. It joins the subject token's refresh token family, so a replayed refresh token that revokes the family revokes it too. Its lifetime is the client's AccessTokenExpiresIn, capped at the subject token's expiry, so a chain of exchanges never outlives the token it started from. A subject token too close to its expiry to leave the new token any lifetime is refused with invalid_request.
Once the user signs out, or the session or the family is revoked, the authorization server refuses the new token: introspection reports it inactive, and a further exchange of it fails. An API that validates the JWT itself, as the inventory API above does, keeps accepting it until it expires, so keep AccessTokenExpiresIn short for clients that exchange tokens, or have the API introspect the token (RFC 7662) where access has to stop at once.
Impersonation and delegation
RFC 8693, section 1.1 distinguishes them by what the new token says about who acts. Under impersonation the token names the user as its subject and no actor: the API sees the user, and the token's client_id tells it only which service exchanged it. Under delegation the token also names the party acting for the user, in the act claim (section 4.1).
The request decides which one you get:
- Without an
actor_token, no actor is added. The new token copies the subject token's ownactchain as it is: exchanged from a plain user token, it is impersonation, and exchanged from a delegated token, it keeps that delegation. - With an
actor_token, the exchange is delegation. The actor token's subject becomes the current actor,{"sub": "<actor>"}, and the subject token's earlier chain nests inside it, so the outermostactis always the party acting now.
The actor token is usually the service's own access token from the client credentials grant, so the client lists client_credentials in AllowedGrantTypes too. In a chain of services, each one presents its own actor token when it exchanges, and the last API sees every hop in act; a hop that presents none leaves no trace of itself.
For a pairwise client every actor appears under that client's pseudonym, as sub does. Introspection returns act to every authorized caller, so a resource server can see that a token is delegated and how deep the chain is. The client the token was issued to sees act as issued; another pairwise caller sees the actors under its own pseudonyms, and any other caller sees the chain without the actors' identifiers.
Whose tokens a client may exchange
A client presenting a token issued to someone else is a confused deputy: given the chance, it would turn a token meant for another party into one of its own. CrossClientSubjectTokenExchange decides how far a client is trusted:
Refused, the default: the subject token must have been issued to the client presenting it. A token whose client cannot be determined is refused too.AddressedToClient: the client may also exchange another client's access token when itsaudnames one of the client'sResourceLocations, compared as exact strings. That token was issued for this client acting as a resource server, which is the case of an API or an MCP server calling further downstream. Refresh tokens and ID tokens are not addressed to a resource, so only the client they were issued to can exchange them.Any: a broker trusted with any subject or actor token, whichever client it was issued to.
An actor token identifies the party acting, so under Refused and AddressedToClient it must be the presenting client's own: a resource server delegating downstream acts as itself. Only Any accepts an actor token issued to another client.
Two client settings stop the host at startup: AddressedToClient with no ResourceLocations, because no token would ever be addressed to that client, and ResourceLocations that name the issuer, because the issuer is the audience of tokens whose request named no target, so it would admit them all. A tenant read from a store with such a client is left out, and the other tenants are served.
Choose the target
The target goes straight into the new token's aud, so it is limited per client. TokenExchangeAllowedAudiences lists the values a client may ask for. Without that list, any request carrying audience is refused with invalid_target, and a resource value goes through the same checks as at every other grant: it must be a resource the tenant declares.
Once a client has TokenExchangeAllowedAudiences, every audience and every resource of its requests must be in it, so naming the target as a resource instead does not get around the list. A refused request names every value that is not allowed.
Errors
A subject or actor token that a resolver or the origin check rejects is refused with invalid_request, as RFC 8693, section 2.2.2 requires, even when a host's own resolver returned another code. Only server_error and temporarily_unavailable pass through unchanged, because they say the server could not judge the token, not that the token is bad. The description of such a refusal starts with subject_token: or actor_token: , which says which token was meant; the table shows it without that prefix. The other rows are sent as shown.
| Error description | Code | Cause |
|---|---|---|
Client is not permitted to use the Token Exchange grant. | invalid_request | The client's TokenExchangeAllowedSubjectTokenTypes is an empty list. |
subject_token_type '...' is not in the client's allow list. | invalid_request | The type is missing from TokenExchangeAllowedSubjectTokenTypes; the same text names actor_token_type for an actor token. |
actor_token and actor_token_type must be supplied together. | invalid_request | One of the two is missing. |
requested_token_type '...' is not supported (only access_token issued). | invalid_request | A token type other than an access token was requested. |
token_type '...' is not supported. | invalid_request | No resolver is registered for the type. |
The token was issued to a different client than the one presenting it. | invalid_request | Another client's token under Refused, or under AddressedToClient when its aud names none of the client's ResourceLocations. |
The client the token was issued to could not be determined. | invalid_request | The token names no client, and the client is not set to Any. |
The token names no session, so a revocation of its session could not be checked. | invalid_request | A JWT without sid, such as an ID token of a client with neither back-channel logout nor front-channel logout with RequiresSessionId. |
The token states no authentication time, so the token exchanged from it could not state one. | invalid_request | A JWT without auth_time. |
The token's client is not known. | invalid_request | The token names a client the server no longer knows. |
The token is invalid or has expired. | invalid_request | A bad signature, an expired or revoked token, a JWT whose session was signed out or revoked, or a refresh token the server no longer honors. |
The session the token was issued in has been revoked. | invalid_request | A refresh token whose session was signed out or revoked. |
The grant expired before a token could be issued under it. | invalid_request | The subject token expires too soon to leave the new token any lifetime. |
Authorization request committed to a DPoP key but no proof was presented. | invalid_dpop_proof | A DPoP-bound subject token exchanged by its own client without a proof. |
The grant is bound to a client certificate that was not presented on this request. | invalid_grant | A certificate-bound subject token exchanged without that certificate. |
The client is not permitted to request an audience for token exchange. | invalid_target | An audience from a client without TokenExchangeAllowedAudiences. |
The following target services are not in the client's allow list: ... | invalid_target | An audience or resource missing from TokenExchangeAllowedAudiences. |
None of the requested scopes can be granted to this client for the resources the token is issued for. | invalid_scope | Every requested scope was dropped, for example because the subject token does not hold it. |
Next steps
- Secure an MCP Server shows where token exchange fits behind an MCP server.
- Token inventory and revocation explains how sessions and refresh token families revoke the tokens issued from them.