Client credentials and service-to-service calls

This documentation was generated with the assistance of AI. Please report any inaccuracies.

service-client is a command-line application that calls the resource server as a client, not as a user. It has the hexagonal layout of the other applications: domain (the Document model and the ports DocumentGateway and OnBehalfOfDocumentGateway), application (ListDocumentsUseCase, ListDocumentsOnBehalfOfUseCase), infrastructure/resourceserver (the only module with Spring Security and the client generated from the resource server’s contract) and boot (one runner per profile). Profiles: device-flow (see Device authorization grant), client-credentials and token-exchange.

Client credentials

The client-credentials profile (ClientCredentialsCli) obtains a token with the client_credentials grant and lists GET /api/documents. The token is cached by an AuthorizedClientServiceOAuth2AuthorizedClientManager and renewed when less than service-client.auth.refresh-before (default PT60S) of its life is left.

        final var clientCredentials = OAuth2AuthorizedClientProviderBuilder.builder()
                .clientCredentials(grant -> grant
                        .accessTokenResponseClient(tokenClients.clientCredentials())
                        .clockSkew(properties.refreshBefore()))
                .build();
        final var clientCredentialsManager =
                new AuthorizedClientServiceOAuth2AuthorizedClientManager(registrations, clients);
        clientCredentialsManager.setAuthorizedClientProvider(clientCredentials);

Settings come from the environment (SERVICE_CLIENT_ID, SERVICE_CLIENT_SECRET, SERVICE_CLIENT_TOKEN_URI, SERVICE_CLIENT_RESOURCE_SERVER_URI, SERVICE_CLIENT_AUTH_METHOD, SERVICE_CLIENT_DPOP). With SERVICE_CLIENT_PRINT_ACCESS_TOKEN=true the access token is printed too.

Client authentication methods

service-client.auth.method How the client proves its identity

client_secret_basic

The registered secret, in the HTTP Basic header.

private_key_jwt

A signed assertion (RFC 7523). The key is an unencrypted PKCS#8 PEM in SERVICE_CLIENT_PRIVATE_KEY or a file path; the server holds only the public JWK set (jwks of the client) or a jwkSetUrl. No key is committed anywhere.

tls_client_auth

The client certificate of a mutual-TLS connection (RFC 8705), taken from the SSL bundle named by ssl-bundle.

self_signed_tls_client_auth

A self-signed certificate pinned through the client’s registered JWKs (x5c).

    /**
     * Reads the key and builds its JWK.
     *
     * @param registration the registration the assertion is for, which is not needed to choose the key.
     * @return the signing JWK.
     * @throws IllegalStateException if no key is configured or it cannot be read as an unencrypted PKCS#8 RSA key.
     */
    @Override
    public JWK apply(final ClientRegistration registration) {
        final var pem = readPem();
        if (pem.contains(PKCS1_HEADER)) {
            throw new IllegalStateException("The private key must be PKCS#8 (BEGIN PRIVATE KEY), not PKCS#1");
        }
        try {
            final var der = Base64.getDecoder().decode(pem.replaceAll(PEM_MARKER, "").replaceAll("\\s", ""));
            final var factory = KeyFactory.getInstance("RSA");
            if (!(factory.generatePrivate(new PKCS8EncodedKeySpec(der)) instanceof RSAPrivateCrtKey privateKey)) {
                throw new IllegalStateException("The private key is not an RSA private key with CRT parameters");
            }
            final var publicKey = (RSAPublicKey) factory.generatePublic(
                    new RSAPublicKeySpec(privateKey.getModulus(), privateKey.getPublicExponent()));
            return new RSAKey.Builder(publicKey)
                    .privateKey(privateKey)
                    .keyUse(KeyUse.SIGNATURE)
                    .algorithm(JWSAlgorithm.RS256)
                    .keyID(properties.keyId())
                    .build();
        } catch (final IllegalArgumentException | GeneralSecurityException e) {
            throw new IllegalStateException("The private key is not a valid unencrypted PKCS#8 RSA key", e);
        }
    }

Server side

A client assertion must carry jti and iat and live at most authserver.client-assertion.max-lifetime (default PT5M); Spring Authorization Server requires neither and has no replay store, so the server adds both. Each (client_id, jti) is recorded once in client_assertion_jtis and a replay is refused with invalid_client.

-- One row per client assertion (private_key_jwt) already accepted, so the same assertion cannot be presented twice
-- (RFC 7523 section 3 allows an authorization server to refuse a replayed jti). A row is useful only until the
-- assertion expires and is purged afterwards.
CREATE TABLE client_assertion_jtis
(
    client_id  varchar(100)             NOT NULL,
    jti        varchar(255)             NOT NULL,
    expires_at timestamp with time zone NOT NULL,
    PRIMARY KEY (client_id, jti)
);

CREATE INDEX ix_client_assertion_jtis_expires_at ON client_assertion_jtis (expires_at);
/**
 * Validates what the framework's default assertion validators leave out: the assertion must carry a {@code jti}, an
 * {@code iat} no later than now (within the same clock skew the framework's timestamp validator allows) and an
 * {@code exp} no more than the configured maximum lifetime after it, so a future {@code iat} cannot stretch the
 * window, and its {@code jti} must not
 * have been used before by the same client (RFC 7523, section 3). The use is recorded last, only for an assertion
 * that passed the other checks, so a refused assertion never consumes its identifier. The record is made through
 * {@link RegisterClientAssertionUseCase}, so the replay protection is shared by every instance of the server.
 */
@RequiredArgsConstructor
public class ReplayRejectingJwtValidator implements OAuth2TokenValidator<Jwt> {

    /** Description of the failures. */
    private static final String DESCRIPTION_PREFIX = "The client assertion ";

    /** Clock skew tolerated for {@code iat}, the default of the framework's {@code JwtTimestampValidator}. */
    private static final Duration CLOCK_SKEW = Duration.ofSeconds(60);

    /** Remembers the assertions that were accepted. */
    private final RegisterClientAssertionUseCase registerClientAssertion;

    /** Settings of the client assertions, for the longest lifetime. */
    private final ClientAssertionProperties properties;

    /** Source of the current instant. */
    private final Clock clock;

    /**
     * Checks the assertion and records its use.
     *
     * @param jwt the assertion, already verified for signature, issuer, subject, audience and expiry.
     * @return success, or a failure when the {@code jti}, {@code iat} or {@code exp} is missing, {@code iat} is in
     *         the future, the lifetime is
     *         longer than allowed or the {@code jti} was already used.
     */
    @Override
    public OAuth2TokenValidatorResult validate(final Jwt jwt) {
        if (!StringUtils.hasText(jwt.getId())) {
            return failure("must have a jti");
        }
        final var issuedAt = jwt.getIssuedAt();
        final var expiresAt = jwt.getExpiresAt();
        if (issuedAt == null) {
            return failure("must have an iat");
        }
        if (expiresAt == null) {
            return failure("must have an exp");
        }
        if (issuedAt.isAfter(clock.instant().plus(CLOCK_SKEW))) {
            return failure("is issued in the future");
        }
        final var maxLifetime = properties.maxLifetime();
        if (Duration.between(issuedAt, expiresAt).compareTo(maxLifetime) > 0) {
            return failure("lives longer than " + maxLifetime);
        }
        final var clientId = jwt.getSubject();
        if (!StringUtils.hasText(clientId)) {
            return failure("must have a sub");
        }
        if (!registerClientAssertion.execute(new ClientAssertionUse(clientId, jwt.getId(), expiresAt))) {
            return failure("was already used");
        }
        return OAuth2TokenValidatorResult.success();
    }

    /**
     * Builds a failure.
     *
     * @param reason what is wrong with the assertion.
     * @return the failed result.
     */
    private static OAuth2TokenValidatorResult failure(final String reason) {
        return OAuth2TokenValidatorResult.failure(
                new OAuth2Error(OAuth2ErrorCodes.INVALID_CLIENT, DESCRIPTION_PREFIX + reason, null));
    }
}
/**
 * Creates the decoder of the client assertions of a client. A client with a registered JWK set
 * ({@code settings.client.jwks}) is verified against those keys; any other client goes through the framework's
 * factory, which reads the keys of its {@code jwkSetUrl} (or the shared secret of {@code client_secret_jwt}). Both
 * add the framework's default assertion validators (issuer, subject, audience including the PAR endpoint, expiry)
 * and the {@link ReplayRejectingJwtValidator}. The framework's own factory caches a decoder per client forever, so
 * this one caches the decoders itself, per client identifier and a hash of the settings that decide the keys, and a
 * client whose keys or algorithm were changed is verified against the new ones.
 */
@RequiredArgsConstructor
public class RegisteredJwksClientAssertionDecoderFactory implements JwtDecoderFactory<RegisteredClient> {

    /** Name of the custom client setting that holds the registered public JWK set as JSON. */
    public static final String JWKS_SETTING = "settings.client.jwks";

    /** Most decoders kept. */
    private static final long MAX_DECODERS = 1_000L;

    /** Time an unused decoder is kept. */
    private static final Duration IDLE = Duration.ofMinutes(10);

    /** Separator of the fields hashed into a cache key. */
    private static final char SEPARATOR = '\u0000';

    /** Algorithm of the settings hash. */
    private static final String HASH_ALGORITHM = "SHA-256";

    /** Records the use of an assertion and checks its lifetime. */
    private final ReplayRejectingJwtValidator replayValidator;

    /** Decoders by client and settings hash. */
    private final Cache<String, JwtDecoder> decoders = Caffeine.newBuilder().maximumSize(MAX_DECODERS)
            .expireAfterAccess(IDLE).build();

    /**
     * Returns the decoder of the assertions of a client.
     *
     * @param registeredClient the client that authenticates.
     * @return the decoder, which also rejects a replayed assertion.
     * @throws OAuth2AuthenticationException {@code invalid_client} if the client has registered keys but no signing
     *                                       algorithm, or the keys cannot be read; the framework's factory throws it
     *                                       too when it has no way to find the keys.
     */
    @Override
    public JwtDecoder createDecoder(final RegisteredClient registeredClient) {
        return decoders.get(cacheKey(registeredClient), key -> build(registeredClient));
    }

    /**
     * Builds a decoder.
     *
     * @param registeredClient the client that authenticates.
     * @return the decoder.
     */
    private JwtDecoder build(final RegisteredClient registeredClient) {
        final var validators = validatorsOf(registeredClient);
        final var jwks = registeredClient.getClientSettings().<Object>getSetting(JWKS_SETTING);
        if (!(jwks instanceof String json) || !StringUtils.hasText(json)) {
            final var framework = new JwtClientAssertionDecoderFactory();
            framework.setJwtValidatorFactory(client -> validators);
            return framework.createDecoder(registeredClient);
        }
        final var algorithm = registeredClient.getClientSettings().getTokenEndpointAuthenticationSigningAlgorithm();
        if (algorithm == null) {
            throw invalidClient("The token endpoint signing algorithm of the client is not registered");
        }
        final var signatureAlgorithm = SignatureAlgorithm.from(algorithm.getName());
        if (signatureAlgorithm == null) {
            throw invalidClient("The token endpoint signing algorithm of the client is not an asymmetric one");
        }
        final JWKSet keys;
        try {
            keys = JWKSet.parse(json);
        } catch (ParseException e) {
            throw invalidClient("The registered keys of the client cannot be read");
        }
        final var decoder = NimbusJwtDecoder.withJwkSource(new ImmutableJWKSet<SecurityContext>(keys))
                .jwsAlgorithm(signatureAlgorithm).build();
        decoder.setJwtValidator(validators);
        return decoder;
    }

    /**
     * Combines the default assertion validators with the replay one, failing fast so the replay validator only runs
     * (and only records the {@code jti}) for an assertion that passed every default check.
     *
     * @param registeredClient the client that authenticates.
     * @return the validator.
     */
    private OAuth2TokenValidator<Jwt> validatorsOf(final RegisteredClient registeredClient) {
        final var defaults = JwtClientAssertionDecoderFactory.DEFAULT_JWT_VALIDATOR_FACTORY.apply(registeredClient);
        final var validators = new DelegatingOAuth2TokenValidator<>(defaults, replayValidator);
        validators.setFailOnError(true);
        return validators;
    }

    /**
     * Builds the cache key: the client identifier and the hash of everything that decides which keys verify it.
     *
     * @param registeredClient the client that authenticates.
     * @return the key.
     */
    private static String cacheKey(final RegisteredClient registeredClient) {
        final var settings = registeredClient.getClientSettings();
        final var algorithm = settings.getTokenEndpointAuthenticationSigningAlgorithm();
        final var material = String.join(String.valueOf(SEPARATOR),
                String.valueOf(settings.<Object>getSetting(JWKS_SETTING)),
                String.valueOf(settings.getJwkSetUrl()),
                algorithm == null ? "" : algorithm.getName(),
                String.valueOf(registeredClient.getClientSecret()));
        try {
            final var hash = MessageDigest.getInstance(HASH_ALGORITHM)
                    .digest(material.getBytes(StandardCharsets.UTF_8));
            return registeredClient.getClientId() + SEPARATOR + HexFormat.of().formatHex(hash);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException(HASH_ALGORITHM + " is always available", e);
        }
    }

    /**
     * Builds the {@code invalid_client} error.
     *
     * @param description what is wrong.
     * @return the exception.
     */
    private static OAuth2AuthenticationException invalidClient(final String description) {
        return new OAuth2AuthenticationException(
                new OAuth2Error(OAuth2ErrorCodes.INVALID_CLIENT, description, null));
    }
}
/**
 * Verifies the certificate a client presented on the TLS port (RFC 8705), replacing the framework's verifier, which
 * has no trust anchors of its own.
 * <ul>
 * <li>{@code tls_client_auth}: the chain must validate (PKIX path validation) against the configured trust anchors,
 * and the subject DN of the leaf must equal the one registered for the client. Revocation checking is disabled: it
 * needs a CRL or OCSP endpoint reachable from the server, which this example does not assume. No configured anchor
 * means no client is accepted.</li>
 * <li>{@code self_signed_tls_client_auth}: the certificate must be self-signed and its public key one of the keys of
 * the client's registered JWK set; otherwise the decision is the framework's own (which compares it with the keys of
 * the client's {@code jwkSetUrl}), whose provider is {@code defaultProvider}.</li>
 * </ul>
 * Every refusal is {@code invalid_client}.
 */
@RequiredArgsConstructor
public class ClientCertificateVerifier implements Consumer<OAuth2ClientAuthenticationContext> {

    /** Type of the certification path. */
    private static final String CERTIFICATE_TYPE = "X.509";

    /** Algorithm of the path validation. */
    private static final String PKIX = "PKIX";

    /** The trusted certificate authorities. */
    private final MtlsTrustAnchors trustAnchors;

    /** A default-configured provider of the framework, asked about a self-signed certificate with no registered key. */
    private final AuthenticationProvider defaultProvider;

    /**
     * Verifies the certificate of the client.
     *
     * @param context the client and its authentication.
     * @throws OAuth2AuthenticationException {@code invalid_client} if the certificate is not accepted.
     */
    @Override
    public void accept(final OAuth2ClientAuthenticationContext context) {
        final OAuth2ClientAuthenticationToken authentication = context.getAuthentication();
        final var method = authentication.getClientAuthenticationMethod();
        final var chain = chainOf(authentication);
        if (ClientAuthenticationMethod.TLS_CLIENT_AUTH.equals(method)) {
            verifyCaIssued(context, chain);
        } else if (ClientAuthenticationMethod.SELF_SIGNED_TLS_CLIENT_AUTH.equals(method)) {
            verifySelfSigned(context, authentication, chain);
        } else {
            throw invalidClient();
        }
    }

    /**
     * Verifies a certificate issued by a trusted authority.
     *
     * @param context the client and its authentication.
     * @param chain   the presented chain, the leaf first.
     */
    private void verifyCaIssued(final OAuth2ClientAuthenticationContext context, final X509Certificate[] chain) {
        if (trustAnchors.anchors().isEmpty()) {
            throw invalidClient();
        }
        final var leaf = chain[0];
        // the leaf is the certificate whose key the TLS handshake proved and whose DN is compared below: it must be
        // the first certificate of the validated path, never an anchor left out of it
        if (isAnchor(leaf)) {
            throw invalidClient();
        }
        final var path = Arrays.stream(chain).filter(certificate -> !isAnchor(certificate)).toList();
        try {
            final var parameters = new PKIXParameters(trustAnchors.anchors());
            parameters.setRevocationEnabled(false);
            CertPathValidator.getInstance(PKIX).validate(
                    CertificateFactory.getInstance(CERTIFICATE_TYPE).generateCertPath(path), parameters);
        } catch (GeneralSecurityException e) {
            throw invalidClient();
        }
        final var expected = context.getRegisteredClient().getClientSettings().getX509CertificateSubjectDN();
        if (!StringUtils.hasText(expected) || !expected.equals(leaf.getSubjectX500Principal().getName())) {
            throw invalidClient();
        }
    }

    /**
     * Verifies a self-signed certificate.
     *
     * @param context        the client and its authentication.
     * @param authentication the client authentication.
     * @param chain          the presented chain, the leaf first.
     */
    private void verifySelfSigned(final OAuth2ClientAuthenticationContext context,
                                  final OAuth2ClientAuthenticationToken authentication,
                                  final X509Certificate[] chain) {
        final var leaf = chain[0];
        if (leaf.getIssuerX500Principal().equals(leaf.getSubjectX500Principal())
                && matchesRegisteredKey(context, leaf.getPublicKey())) {
            return;
        }
        // the result is not needed: the provider throws invalid_client when the certificate does not match
        defaultProvider.authenticate(authentication);
    }

    /**
     * Tells whether a key is one of the registered JWK set of the client.
     *
     * @param context the client and its authentication.
     * @param key     the public key of the certificate.
     * @return {@code true} when a registered key equals it.
     */
    private boolean matchesRegisteredKey(final OAuth2ClientAuthenticationContext context, final PublicKey key) {
        final var jwks = context.getRegisteredClient().getClientSettings()
                .<Object>getSetting(RegisteredJwksClientAssertionDecoderFactory.JWKS_SETTING);
        if (!(jwks instanceof String json) || !StringUtils.hasText(json)) {
            return false;
        }
        try {
            for (final JWK jwk : JWKSet.parse(json).getKeys()) {
                if (jwk instanceof AsymmetricJWK asymmetric && Arrays.equals(asymmetric.toPublicKey().getEncoded(),
                        key.getEncoded())) {
                    return true;
                }
            }
            return false;
        } catch (ParseException | JOSEException e) {
            return false;
        }
    }

    /**
     * Tells whether a certificate is itself a trust anchor, which a certification path must not contain.
     *
     * @param certificate the certificate.
     * @return {@code true} when an anchor holds exactly that certificate.
     */
    private boolean isAnchor(final X509Certificate certificate) {
        return trustAnchors.anchors().stream().anyMatch(anchor -> certificate.equals(anchor.getTrustedCert()));
    }

    /**
     * Reads the presented chain.
     *
     * @param authentication the client authentication.
     * @return the chain, the leaf first.
     */
    private static X509Certificate[] chainOf(final Authentication authentication) {
        if (authentication.getCredentials() instanceof X509Certificate[] chain && chain.length > 0) {
            return chain;
        }
        throw invalidClient();
    }

    /**
     * Builds the refusal.
     *
     * @return the {@code invalid_client} exception.
     */
    private static OAuth2AuthenticationException invalidClient() {
        return new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_CLIENT));
    }
}
/**
 * Installs {@code private_key_jwt} with replay protection and the mutual-TLS client authentication in the protocol
 * chain: the framework's assertion provider decodes with {@link RegisteredJwksClientAssertionDecoderFactory}, and its
 * certificate provider verifies with {@link ClientCertificateVerifier}. The server metadata (the OpenID provider
 * configuration and the OAuth 2.0 authorization server metadata) also advertises {@code mtls_endpoint_aliases}.
 */
@RequiredArgsConstructor
public class ClientAuthProtocolChainCustomizer implements ProtocolChainCustomizer {

    /** Order of the customizer: after the multi-factor, step-up and device ones. */
    public static final int ORDER = 3;

    /** Creates the decoders of the client assertions. */
    private final RegisteredJwksClientAssertionDecoderFactory decoderFactory;

    /** Verifies the client certificates. */
    private final ClientCertificateVerifier certificateVerifier;

    /** Builds the {@code mtls_endpoint_aliases} claim. */
    private final MtlsEndpointAliases endpointAliases;

    /**
     * Customizes the client authentication and the metadata.
     *
     * @param server configurer of the authorization server.
     */
    @Override
    public void customize(final OAuth2AuthorizationServerConfigurer server) {
        server.clientAuthentication(client -> client.authenticationProviders(this::configure));
        server.authorizationServerMetadataEndpoint(metadata -> metadata.authorizationServerMetadataCustomizer(
                builder -> endpointAliases.contribute(builder::claim)));
        server.oidc(oidc -> oidc.providerConfigurationEndpoint(configuration ->
                configuration.providerConfigurationCustomizer(builder -> endpointAliases.contribute(builder::claim))));
    }

    /**
     * Sets the decoder factory and the certificate verifier on the framework's providers.
     *
     * @param providers the providers of the client authentication.
     */
    private void configure(final List<AuthenticationProvider> providers) {
        for (final var provider : providers) {
            if (provider instanceof JwtClientAssertionAuthenticationProvider assertions) {
                assertions.setJwtDecoderFactory(decoderFactory);
            } else if (provider instanceof X509ClientCertificateAuthenticationProvider certificates) {
                certificates.setCertificateVerifier(certificateVerifier);
            }
        }
    }
}

tls_client_auth validates the presented chain by PKIX against authserver.mtls.trusted-authorities before comparing the subject DN; with none configured the method is refused. The dedicated TLS port accepts any chain so that clients of private authorities can present one, which makes this check the trust decision.

The PKIX validation does not check revocation (no CRL or OCSP).
  client-assertion:
    # private_key_jwt / client_secret_jwt client authentication (RFC 7523): the longest lifetime accepted for an
    # assertion (exp minus iat), and the jti replay records are purged after they expire.
    max-lifetime: PT5M
    cleanup:
      # when the expired assertion identifiers are deleted (every hour)
      cron: "0 30 * * * *"
  mtls:
    # Mutual-TLS client authentication (RFC 8705): the certificate authorities, as PEM or key store locations, whose
    # certificates are accepted for tls_client_auth. Empty: none, only self_signed_tls_client_auth can succeed.
    trusted-authorities: []

Certificate-bound and DPoP-bound tokens

A client registered with certificateBoundAccessTokens gets cnf.x5t#S256 in its tokens; a token request carrying a DPoP proof gets token_type=DPoP and cnf.jkt. The resource server rejects a bound token used without the matching certificate or proof (see Resource server). Spring Security has no client-side DPoP, so service-client builds its proofs with Nimbus (DPoPProofs).

    @Override
    public ClientHttpResponse intercept(final HttpRequest request, final byte[] body,
            final ClientHttpRequestExecution execution) throws IOException {
        final var authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId(registrationId)
                .principal(principal)
                .build();
        final var authorizedClient = manager.authorize(authorizeRequest);
        if (authorizedClient == null) {
            throw new ClientAuthorizationException(new OAuth2Error(OAuth2ErrorCodes.ACCESS_DENIED,
                    "The service client has no access token", null), registrationId);
        }
        final var token = authorizedClient.getAccessToken();
        if (OAuth2AccessToken.TokenType.DPOP.equals(token.getTokenType())) {
            request.getHeaders().set(HttpHeaders.AUTHORIZATION, DPOP_SCHEME + token.getTokenValue());
            request.getHeaders().set(DPOP_HEADER,
                    proofs.proof(request.getMethod().name(), request.getURI(), token.getTokenValue()));
        } else {
            request.getHeaders().setBearerAuth(token.getTokenValue());
        }
        return execution.execute(request, body);
    }

Token exchange (RFC 8693)

The token-exchange profile (TokenExchangeCli) takes the access token of a user from SERVICE_CLIENT_SUBJECT_TOKEN, uses its own client-credentials token as the actor_token and calls GET /api/documents as that user: sub stays the user and the token carries act.sub = the service client. The client needs the grant urn:ietf:params:oauth:grant-type:token-exchange.

        // 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();
        });

The server’s provider ignores the audience parameter, so a contributor keeps the requested audiences that are in the client’s own list and never widens it.

/**
 * 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);
    }
}

The generated client behind the gateways is described in the apis/README.md of the repository.