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.

At a glance
  • 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 of service-client, registered through POST /api/admin/clients with the grant types client_credentials and urn:ietf:params:oauth:grant-type:token-exchange, the scope documents.read and the audience resource-server.

  • Preconditions: Spring profile token-exchange on service-client; the user’s access token, issued by this server, in SERVICE_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

  1. TokenExchangeCli (profile token-exchange) reads the subject token from SERVICE_CLIENT_SUBJECT_TOKEN and fails with a clear message when it is empty.

  2. It runs ListDocumentsOnBehalfOfUseCase, which calls the port OnBehalfOfDocumentGateway, implemented by RestOnBehalfOfDocumentGateway. The call’s principal is the user’s token (PrincipalMapper.user), and the registration is service-client-token-exchange (ServiceClientRegistrationMapper).

  3. The authorized client manager of OAuth2ClientConfiguration uses a TokenExchangeOAuth2AuthorizedClientProvider. 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).

  4. The provider posts to /oauth2/token: grant_type=urn:ietf:params:oauth:grant-type:token-exchange, subject_token (the user’s token) with subject_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.

  5. 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 is invalid_grant), validates the actor token, honours a may_act claim of the subject token if present, and builds a composite principal: the user, acted on by the client.

  6. The token customizers run. IssuedTokenClaims adds the user’s roles and tenant and the client’s configured audiences. TokenExchangeAudienceContributor (a JwtClaimsContributor, order 120) runs only for an access token of this grant whose request named an audience: it keeps the requested audiences that are in the client’s settings.client.audiences and answers invalid_target when none is. It never widens aud.

  7. 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 as sub and returns that user’s documents.

  8. With SERVICE_CLIENT_PRINT_ACCESS_TOKEN=true the 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);
    }
}
sequenceDiagram autonumber participant U as User via BFF participant S as service-client participant A as auth-server participant R as resource-server U-->>S: user access token in SERVICE_CLIENT_SUBJECT_TOKEN S->>A: POST /oauth2/token grant_type=client_credentials A-->>S: actor token, sub = client id S->>A: POST /oauth2/token grant_type=token-exchange, subject_token, actor_token A->>A: authenticate client, check token-exchange grant A->>A: find authorization of subject token, validate actor token, check may_act A->>A: claims: sub = user, act.sub = client, roles, tenant, aud narrowed A-->>S: 200 access_token, issued_token_type=access_token S->>R: GET /api/documents with Authorization Bearer exchanged token R-->>S: 200 documents of the user
flowchart TD Q[Token exchange request] --> G{"Client has token-exchange grant?"} G -- No --> E1["400 unauthorized_client"] G -- Yes --> S{"Subject token issued by this server and active?"} S -- No --> E2["400 invalid_grant"] S -- Yes --> M{"may_act present?"} M -- "Yes, excludes actor" --> E2 M -- "No, or names actor" --> A{"audience requested?"} A -- No --> T["aud = client audiences"] A -- Yes --> N{"Any requested audience in client audiences?"} N -- No --> E3["400 invalid_target"] N -- Yes --> T2["aud = requested and allowed audiences"] T --> OK["Token: sub user, act client"] T2 --> OK

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’s sub, the local username).

  • act: {"sub": "<exchanging client id>"}, written by the framework.

  • roles and tenant: 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: TokenExchangeIT checks a valid exchange (sub user, act.sub client, aud narrowed), an audience that is not allowed (invalid_target), a client without the grant (unauthorized_client), a foreign subject token (invalid_grant) and a may_act claim that excludes or names the actor.

  • service-client/infrastructure/resourceserver: ResourceServerAdapterIT (listDocumentsAs_whenUserTokenIsGiven_exchangesItWithTheClientTokenAsActor).

  • e2e-tests: TokenExchangeEndToEndIT signs the demo user in through the BFF, runs the packaged service-client with the user’s token and checks sub, act.sub, aud and scope; a foreign subject token makes the tool fail.