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.
-
Actors: a confidential client (here
service-client),auth-server. -
Clients involved: any client registered through
POST /api/admin/clientswithauthMethodsset. Only a client with aclient_secret_*method gets a generated secret. -
Preconditions:
-
private_key_jwt:jwks(public keys only, else400 invalid-jwks) orjwkSetUrl, andtokenEndpointAuthSigningAlgorithm;authserver.client-assertion.max-lifetime(defaultPT5M). -
tls_client_auth:tlsClientAuthSubjectDn;authserver.mtls.trusted-authorities(empty by default, which refuses the method); the TLS connector of the server (authserver.x509.enabled=trueandauthserver.x509.port). -
self_signed_tls_client_auth:jwksholding the certificate’s public key, orjwkSetUrl; 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
-
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_secretform parameter (client_secret_post),client_assertionplusclient_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer(private_key_jwtandclient_secret_jwt), or a TLS client certificate on the connection (mutual TLS methods). -
The client is loaded by
client_idand the method used must be one it is registered for, else401 invalid_client. -
ClientAuthProtocolChainCustomizer(aProtocolChainCustomizer, order 3, declared byClientAuthConfiguration) replaces two pieces of the framework providers, with no edit ofSecurityConfig:-
on
JwtClientAssertionAuthenticationProviderit setsRegisteredJwksClientAssertionDecoderFactoryas the JWT decoder factory; -
on
X509ClientCertificateAuthenticationProviderit setsClientCertificateVerifieras the certificate verifier.
-
-
client_secret_basic: the secret is compared with the stored hash.
service-clientsends it fromSERVICE_CLIENT_SECRET. -
private_key_jwt:
-
RegisteredJwksClientAssertionDecoderFactorybuilds (and caches with Caffeine) a decoder per client. With a registered JWK set (client settingsettings.client.jwks) it verifies the signature with those keys and the registered algorithm; otherwise it falls back to the framework’sJwtClientAssertionDecoderFactory, which readsjwkSetUrl. -
The framework’s default validators check
issandsub(the client id),aud(the server) and the timestamps. -
ReplayRejectingJwtValidatorthen requiresjti,iatandexp, refuses aniatin the future, refuses a lifetime (exp - iat) aboveauthserver.client-assertion.max-lifetime, and registers(client_id, jti)throughRegisterClientAssertionUseCaseand the portClientAssertionReplayRegistry(JdbcClientAssertionReplayRegistry, tableclient_assertion_jtis,INSERT … ON CONFLICT DO NOTHING). A second use of the samejtiis401 invalid_client. -
ClientAssertionCleanupJobdeletes expired rows onauthserver.client-assertion.cleanup.cron(default0 30 * * * *).
-
-
tls_client_auth:
ClientCertificateVerifiervalidates the presented chain by PKIX against the anchors read fromauthserver.mtls.trusted-authorities(MtlsTrustAnchors, revocation checking off), refuses a leaf that is itself an anchor, then compares the leaf’s subject DN with the registeredtlsClientAuthSubjectDn. The TLS port accepts any chain (AnyClientCertificateTrustManager), so this check is the trust decision. -
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). -
Every failure answers
401witherror=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
A private_key_jwt token request
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_authorself_signed_tls_client_authclient registered withcertificateBoundAccessTokens: truegetscnf.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:ClientAuthenticationITcovers a correct and a wrong secret,private_key_jwtwith registered JWKs and with ajwkSetUrl, a replayed assertion and one that lives too long (bothinvalid_client),tls_client_authwith a trusted and an untrusted authority,self_signed_tls_client_authwith a registered and an unregistered key, and the certificate thumbprint in a bound token. -
auth-server/infrastructure/persistence:JdbcClientAssertionReplayRegistryIT. -
e2e-tests:ClientCredentialsEndToEndITrunsservice-clientwith each of the four methods. -
service-client/infrastructure/resourceserver:ResourceServerAdapterIT(listDocuments_whenMethodIsPrivateKeyJwt_sendsAnAssertionSignedWithTheConfiguredKey).
Specifications
Further reading
-
Client credentials and service-to-service calls (feature page)
-
X.509 client certificates (the TLS port and its trust manager)