In this lesson, you will learn how to implement the OAuth 2.0 Token Exchange pattern to securely swap an existing user token for a new, scoped-down token when calling downstream microservices.
The Token Exchange Pattern
When you build a microservice architecture, a common problem arises: Service A receives a user’s token, but that token is intended for Service A. If Service A needs to call Service B, passing the original token can be dangerous (the "Confused Deputy" problem). Instead of forwarding the broad access token, you perform a Token Exchange.
By using the urn:ietf:params:oauth:grant-type:token-exchange grant type, your service acts as a client to the Identity Provider (IdP). You send the original token to the IdP, which validates it and issues a fresh, restricted token specifically for Service B.
Implementation Concept
In C#, you typically perform this exchange by sending an HTTP POST request to your IdP’s token endpoint. You include the original token as the subject_token and specify the audience (the scope of the downstream service).
var request = new TokenExchangeRequest
{
GrantType = "urn:ietf:params:oauth:grant-type:token-exchange",
SubjectToken = userAccessToken,
SubjectTokenType = "urn:ietf:params:oauth:token-type:access_token",
Audience = "https://api.downstream-service.com"
};
// Send request to IdentityServer/OIDC provider
var response = await _httpClient.RequestTokenExchangeAsync(request);
var downstreamToken = response.AccessToken;
Why use this instead of simple delegation?
If you simply forwarded the user's token, Service B might gain unauthorized access to other services if that token has broad scopes. Token Exchange allows you to practice Least Privilege. The new token is minted by the IdP with a restricted lifetime and minimal scopes required only for that specific interaction. This keeps the "blast radius" small if a downstream service is compromised.
By centralizing this logic within your service-to-service communication layer, you ensure that no service ever handles credentials beyond what it strictly needs to perform its job.
Key Takeaway: Token Exchange mitigates security risks by allowing services to request short-lived, scoped-down tokens from an Identity Provider, ensuring that downstream services only receive the permissions they actually require.