Client authentication

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

A confidential client proves its identity at the token endpoint (and at the introspection, revocation and PAR endpoints) with one of the methods it is registered for. This server supports a shared secret (client_secret_basic, also client_secret_post), a signed JWT assertion (private_key_jwt) and mutual TLS with a certificate issued by a trusted authority (tls_client_auth) or a self-signed one (self_signed_tls_client_auth). Spring Authorization Server provides the methods; this repository adds a replay store and lifetime cap for assertions, registered JWK sets, and the PKIX trust decision for mutual TLS.

At a glance
  • Actors: a confidential client (here service-client), auth-server.

  • Clients involved: any client registered through POST /api/admin/clients with authMethods set. Only a client with a client_secret_* method gets a generated secret.

  • Preconditions:

    • private_key_jwt: jwks (public keys only, else 400 invalid-jwks) or jwkSetUrl, and tokenEndpointAuthSigningAlgorithm; authserver.client-assertion.max-lifetime (default PT5M).

    • tls_client_auth: tlsClientAuthSubjectDn; authserver.mtls.trusted-authorities (empty by default, which refuses the method); the TLS connector of the server (authserver.x509.enabled=true and authserver.x509.port).

    • self_signed_tls_client_auth: jwks holding the certificate’s public key, or jwkSetUrl; the same TLS connector.

  • Endpoints: POST /oauth2/token (and the other client-authenticated protocol endpoints: /oauth2/introspect, /oauth2/revoke, /oauth2/par), on the TLS port for the mutual TLS methods.

Steps

  1. The client sends a token request. Spring Authorization Server’s client authentication filter tries its converters in turn: HTTP Basic header (client_secret_basic), client_secret form parameter (client_secret_post), client_assertion plus client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer (private_key_jwt and client_secret_jwt), or a TLS client certificate on the connection (mutual TLS methods).

  2. The client is loaded by client_id and the method used must be one it is registered for, else 401 invalid_client.

  3. ClientAuthProtocolChainCustomizer (a ProtocolChainCustomizer, order 3, declared by ClientAuthConfiguration) replaces two pieces of the framework providers, with no edit of SecurityConfig:

    1. on JwtClientAssertionAuthenticationProvider it sets RegisteredJwksClientAssertionDecoderFactory as the JWT decoder factory;

    2. on X509ClientCertificateAuthenticationProvider it sets ClientCertificateVerifier as the certificate verifier.

  4. client_secret_basic: the secret is compared with the stored hash. service-client sends it from SERVICE_CLIENT_SECRET.

  5. private_key_jwt:

    1. RegisteredJwksClientAssertionDecoderFactory builds (and caches with Caffeine) a decoder per client. With a registered JWK set (client setting settings.client.jwks) it verifies the signature with those keys and the registered algorithm; otherwise it falls back to the framework’s JwtClientAssertionDecoderFactory, which reads jwkSetUrl.

    2. The framework’s default validators check iss and sub (the client id), aud (the server) and the timestamps.

    3. ReplayRejectingJwtValidator then requires jti, iat and exp, refuses an iat in the future, refuses a lifetime (exp - iat) above authserver.client-assertion.max-lifetime, and registers (client_id, jti) through RegisterClientAssertionUseCase and the port ClientAssertionReplayRegistry (JdbcClientAssertionReplayRegistry, table client_assertion_jtis, INSERT …​ ON CONFLICT DO NOTHING). A second use of the same jti is 401 invalid_client.

    4. ClientAssertionCleanupJob deletes expired rows on authserver.client-assertion.cleanup.cron (default 0 30 * * * *).

  6. tls_client_auth: ClientCertificateVerifier validates the presented chain by PKIX against the anchors read from authserver.mtls.trusted-authorities (MtlsTrustAnchors, revocation checking off), refuses a leaf that is itself an anchor, then compares the leaf’s subject DN with the registered tlsClientAuthSubjectDn. The TLS port accepts any chain (AnyClientCertificateTrustManager), so this check is the trust decision.

  7. self_signed_tls_client_auth: the leaf must be self-issued and its public key must equal a key of the registered JWK set; otherwise the framework’s provider is asked, which pins it through jwkSetUrl (x5c).

  8. Every failure answers 401 with error=invalid_client. On success the token request continues with its grant.

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

Choosing and validating the method

flowchart TD R[Token request] --> Q{"What does it carry?"} Q -- "Basic header" --> SB["client_secret_basic: compare secret hash"] Q -- "client_assertion" --> PK["private_key_jwt"] Q -- "TLS client certificate" --> CM{"Registered method?"} PK --> K{"Registered jwks?"} K -- Yes --> K1[Verify with registered keys and algorithm] K -- No --> K2["Verify with jwkSetUrl (framework factory)"] K1 --> V["Default checks: iss, sub, aud, exp"] K2 --> V V --> RP{"jti and iat present, lifetime within max-lifetime?"} RP -- No --> X["401 invalid_client"] RP -- Yes --> J{"(client_id, jti) new?"} J -- No --> X J -- Yes --> OK[Client authenticated] CM -- tls_client_auth --> T{"Trusted authorities configured?"} T -- No --> X T -- Yes --> P{"PKIX path valid and subject DN matches?"} P -- No --> X P -- Yes --> OK CM -- self_signed_tls_client_auth --> S{"Self-issued and key in registered jwks?"} S -- Yes --> OK S -- No --> F{"Framework pins it through jwkSetUrl?"} F -- Yes --> OK F -- No --> X SB -- match --> OK SB -- mismatch --> X

A private_key_jwt token request

sequenceDiagram autonumber participant S as service-client participant A as auth-server participant D as RegisteredJwksClientAssertionDecoderFactory participant V as ReplayRejectingJwtValidator participant DB as client_assertion_jtis S->>S: sign assertion iss=sub=client_id, aud, jti, iat, exp with private key S->>A: POST /oauth2/token grant_type=client_credentials, client_assertion_type, client_assertion A->>A: load client, check private_key_jwt is registered A->>D: decoder for client D-->>A: decoder over registered jwks or jwkSetUrl A->>A: verify signature and default claims A->>V: validate assertion V->>V: require jti, iat, exp and exp minus iat within max-lifetime V->>DB: INSERT client_id, jti, expires ON CONFLICT DO NOTHING alt row inserted DB-->>V: new V-->>A: valid A-->>S: 200 access token else jti already used DB-->>V: conflict V-->>A: invalid_client A-->>S: 401 invalid_client end

On the client side, service-client with SERVICE_CLIENT_AUTH_METHOD=private_key_jwt reads an unencrypted PKCS#8 PEM key from SERVICE_CLIENT_PRIVATE_KEY or service-client.auth.key.private-key-path; PrivateKeyJwkResolver hands it to Spring Security’s NimbusJwtClientAuthenticationParametersConverter, which TokenEndpointClients adds to the token request. For the mutual TLS methods SERVICE_CLIENT_SSL_BUNDLE names a spring.ssl.bundle.* entry with the client certificate (SslRequestFactories).

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

Tokens and claims

Client authentication does not change the token contents by itself: the client gets the token of its grant (for example the one in Client credentials). Two exceptions:

  • a tls_client_auth or self_signed_tls_client_auth client registered with certificateBoundAccessTokens: true gets cnf.x5t#S256 (the SHA-256 thumbprint of its certificate) in its access token;

  • the assertion itself is never stored, only its (client_id, jti) and expiry.

How it is tested

  • auth-server/boot: ClientAuthenticationIT covers a correct and a wrong secret, private_key_jwt with registered JWKs and with a jwkSetUrl, a replayed assertion and one that lives too long (both invalid_client), tls_client_auth with a trusted and an untrusted authority, self_signed_tls_client_auth with a registered and an unregistered key, and the certificate thumbprint in a bound token.

  • auth-server/infrastructure/persistence: JdbcClientAssertionReplayRegistryIT.

  • e2e-tests: ClientCredentialsEndToEndIT runs service-client with each of the four methods.

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