Token exchange
| This documentation was generated with the assistance of AI. Please report any inaccuracies. |
A service receives a user’s access token and must call another API on that user’s behalf, while making clear that it is
the service doing so. With token exchange (RFC 8693) service-client, started with the token-exchange profile, sends
the user’s token as the subject token and its own client-credentials token as the actor token, and gets a new access
token whose subject is still the user and whose act claim names the client (delegation). The new token keeps the user’s
roles and tenant, and its audience is limited to what the client may target.
-
Actors: the user (who signed in earlier, for example through the BFF),
service-client,auth-server,resource-server. -
Clients involved: the client that obtained the user’s token (for example
bff), and the exchanging confidential client ofservice-client, registered throughPOST /api/admin/clientswith the grant typesclient_credentialsandurn:ietf:params:oauth:grant-type:token-exchange, the scopedocuments.readand the audienceresource-server. -
Preconditions: Spring profile
token-exchangeonservice-client; the user’s access token, issued by this server, inSERVICE_CLIENT_SUBJECT_TOKEN(service-client.cli.subject-token); the client settings of Client credentials (SERVICE_CLIENT_ID,SERVICE_CLIENT_SECRET,SERVICE_CLIENT_TOKEN_URI, …). -
Endpoints:
POST /oauth2/token(twice: client credentials, then token exchange),GET /api/documents.
Steps
-
TokenExchangeCli(profiletoken-exchange) reads the subject token fromSERVICE_CLIENT_SUBJECT_TOKENand fails with a clear message when it is empty. -
It runs
ListDocumentsOnBehalfOfUseCase, which calls the portOnBehalfOfDocumentGateway, implemented byRestOnBehalfOfDocumentGateway. The call’s principal is the user’s token (PrincipalMapper.user), and the registration isservice-client-token-exchange(ServiceClientRegistrationMapper). -
The authorized client manager of
OAuth2ClientConfigurationuses aTokenExchangeOAuth2AuthorizedClientProvider. Its actor token resolver first obtains the client’s own client-credentials token through the client-credentials manager (cached and renewed as in Client credentials). -
The provider posts to
/oauth2/token:grant_type=urn:ietf:params:oauth:grant-type:token-exchange,subject_token(the user’s token) withsubject_token_type=urn:ietf:params:oauth:token-type:access_token,actor_token(the client-credentials token) with its type, and the scopes, authenticating the client with its configured method. -
Spring Authorization Server authenticates the client, checks it has the token-exchange grant (else
unauthorized_client), finds the authorization that holds the subject token (a token it did not issue isinvalid_grant), validates the actor token, honours amay_actclaim of the subject token if present, and builds a composite principal: the user, acted on by the client. -
The token customizers run.
IssuedTokenClaimsadds the user’srolesandtenantand the client’s configured audiences.TokenExchangeAudienceContributor(aJwtClaimsContributor, order 120) runs only for an access token of this grant whose request named anaudience: it keeps the requested audiences that are in the client’ssettings.client.audiencesand answersinvalid_targetwhen none is. It never widensaud. -
The exchanged token is cached under the user’s principal and sent as a bearer token (or DPoP) to
GET /api/documents. The resource server sees the user assuband returns that user’s documents. -
With
SERVICE_CLIENT_PRINT_ACCESS_TOKEN=truethe exchanged token is printed too.
service-client itself sends no audience parameter, so its exchanged token carries the client’s configured audiences.
// The builder has no token exchange method, so its provider is added with provider(...). The subject token is
// the principal object of the call (see PrincipalMapper.user) and the actor token is the client's own client
// credentials token, which is how the exchanged token names the client as actor.
final var exchange = new TokenExchangeOAuth2AuthorizedClientProvider();
exchange.setAccessTokenResponseClient(tokenClients.tokenExchange());
exchange.setClockSkew(properties.refreshBefore());
exchange.setActorTokenResolver(context -> {
final var actor = clientCredentialsManager.authorize(OAuth2AuthorizeRequest
.withClientRegistrationId(ServiceClientRegistrationMapper.CLIENT_CREDENTIALS_REGISTRATION_ID)
.principal(principalMapper.serviceClient(properties.clientId()))
.build());
return actor == null ? null : actor.getAccessToken();
});
/**
* Honours the {@code audience} parameter of a token exchange request, which the framework parses but ignores. The
* audiences of an exchanged access token are those the exchanging client may have (its
* {@value IssuedTokenClaims#AUDIENCES_SETTING} setting); when the request names audiences, only the ones among them
* are kept. An audience outside the list of the client is simply not granted, and when none of the requested ones is
* allowed the request is refused with {@value #INVALID_TARGET} (RFC 8693, section 2.2.2), so a narrowed request never
* comes back with every audience of the client. Tokens of any other grant type are not touched.
*/
@Component
@Order(TokenExchangeAudienceContributor.ORDER)
public class TokenExchangeAudienceContributor implements JwtClaimsContributor {
/** Order of the contributor: after the multi-factor ({@code 100}) and identity provider ({@code 110}) ones. */
public static final int ORDER = 120;
/** Error code of an unacceptable target (RFC 8693, section 2.2.2), which the framework has no constant for. */
public static final String INVALID_TARGET = "invalid_target";
@Override
public void contribute(final OAuth2TokenContext context, final Map<String, Object> claims) {
if (!OAuth2TokenType.ACCESS_TOKEN.equals(context.getTokenType())
|| !AuthorizationGrantType.TOKEN_EXCHANGE.equals(context.getAuthorizationGrantType())
|| !(context.getAuthorizationGrant() instanceof OAuth2TokenExchangeAuthenticationToken exchange)
|| exchange.getAudiences().isEmpty()) {
return;
}
final var allowed = context.getRegisteredClient().getClientSettings()
.<Object>getSetting(IssuedTokenClaims.AUDIENCES_SETTING) instanceof List<?> audiences
? audiences : List.of();
// a mutable list on purpose: the authorization store only deserializes allow-listed types
final var granted = allowed.stream().map(String::valueOf).filter(exchange.getAudiences()::contains)
.collect(Collectors.toCollection(ArrayList::new));
if (granted.isEmpty()) {
throw new OAuth2AuthenticationException(new OAuth2Error(INVALID_TARGET,
"None of the requested audiences is allowed for the client", null));
}
claims.put(OAuth2TokenClaimNames.AUD, granted);
}
}
Tokens and claims
-
Token response:
access_token,issued_token_type=urn:ietf:params:oauth:token-type:access_token,token_type,expires_in,scope. -
sub: the user (the subject token’ssub, the local username). -
act:{"sub": "<exchanging client id>"}, written by the framework. -
rolesandtenant: the user’s, as in the subject token. -
aud: the client’s configured audiences, or the requested ones that are among them. -
scope: the granted scopes of the exchanging client.
How it is tested
-
auth-server/boot:TokenExchangeITchecks a valid exchange (subuser,act.subclient,audnarrowed), an audience that is not allowed (invalid_target), a client without the grant (unauthorized_client), a foreign subject token (invalid_grant) and amay_actclaim that excludes or names the actor. -
service-client/infrastructure/resourceserver:ResourceServerAdapterIT(listDocumentsAs_whenUserTokenIsGiven_exchangesItWithTheClientTokenAsActor). -
e2e-tests:TokenExchangeEndToEndITsigns the demo user in through the BFF, runs the packagedservice-clientwith the user’s token and checkssub,act.sub,audandscope; a foreign subject token makes the tool fail.