A simple blog in the complex world of healthcare telematics.
Visit us:
by Nico Mattfeld, reading time:
9 mins
OpenID Connect (OIDC) is highly relevant in today’s software architectures. It allows applications to authenticate users securely without handling any credentials using a standardized protocol. Most frameworks provide out-of-the-box implementations for the OIDC authentication flows which require minimal configuration. Although there are some less common variations that are not fully supported but useful in some environments. The Gematik TI-Gateway specification requires one of those variations.
Every OIDC implementation needs an authentication mechanism to identify the client. The most common way is using a shared client secret. However, the Gematik TI-Gateway specification requires a different authentication method in the OIDC flow: TLS client authentication. Unfortunately, this OIDC authentication method is not fully supported by Spring-Boot, one of the most popular Java Frameworks. This article will show the general concept of this special authentication method in the OIDC flow and how to set up a client and server with Spring Boot, although it is not officially supported.
OpenID Connect (OIDC) is an identity layer built on top of OAuth 2.0 that allows an application to verify a user’s identity and obtain basic information about that user. OIDC provides several authentication flows to achieve this goal. For Web-Applications the most common flow is the Authorization Code Flow where the user is redirected to an Identity Provider to log in. After successful login, the user is redirected back to the application with an authorization code. The application then exchanges this code for a token. As a result, the application identified the user without handling any credentials.
The following diagram shows the Authorization Code Flow more detailed:

User initiates login: The user tries to access an application that requires authentication.
Application redirects the user: The application redirects the user’s browser to the Identity Provider (IdP) with an authentication request. This request includes parameters such as the client ID, redirect URI, requested scopes and security parameters.
Identity Provider authenticates the user: The IdP verifies the user’s identity. In this example the user provides username and password.
Identity Provider returns an authorization code: After successful authentication and authorization, the IdP redirects the user’s browser back to the application with an authorization code.
Application exchanges the code for tokens: The application sends the authorization code to the IdP’s token endpoint.
Identity Provider issues tokens: The IdP returns an ID Token, which contains claims about the authenticated user. It may also return an access token to allow the application to access protected resources.
Application validates the ID Token: The application verifies the token’s signature and relevant claims. If validation succeeds, the application establishes an authenticated session for the user.
User gains access: The application grants access according to the user’s identity and authorization rules.
Client authentication allows the OIDC-Client (application) to prove its identity to the Identity Provider during token exchange. By verifying the identity of clients, the Idp assures that only registered and authorized clients can obtain tokens.
The most common used authentication method is a client secret. A shared secret authenticates the client through a value both parties know. This method is provided by most frameworks and requires only minimal configuration effort.
A more complex method is the TLS client authentication. This method is based on a mutual TLS connection and authenticates the client through a certificate. By relying on asymmetric cryptography and proof of private-key possession rather than a shared secret, this method is suitable for sensitive environments, especially for communication between backend services.
OIDC TLS Client Authentication is a method based on mutual TLS (mTLS). While regular TLS authenticates only the server by sending a certificate to the client, mTLS enforces an additional authentication of the client by requesting a client certificate. After a secured TLS connection has been established, the OIDC layer “reuses” the received client certificate to identify the OIDC client. The server validates the certificate against the registered client identities and rejects requests from unauthorized clients. Nevertheless, it should be noted that only the application is authenticated by the OIDC client authentication, not the end user.
Spring Boot offers a full out-of-the-box OIDC implementation and configuration for clients and servers. It is possible to easily set up a first OIDC client in minutes and configure a matching Spring Boot authorization server. This is really convenient if you need to implement the Authorization Code Flow using a client secret as authentication method. Unfortunately, if you want to use TLS client authentication, there is no ready-to-use implementation for clients in Spring Boot.
The following section will show all necessary modifications and configuration to implement a Spring Boot OIDC client and server using TLS client authentication as OIDC authentication method. Base for the implementation is a default Spring-Boot-OAuth2-Client and a Spring-Boot-Authorization-Server that can be easily set up using the Spring documentation. The following section will only show the parts which need modification or special configuration to enable TLS client authentication.
Let’s start with the easy part: the Spring Boot OIDC Server. The Spring OAuth2-Authorization-Server includes all the necessary implementations for using TLS client authentication. Unfortunately, it is quite difficult to find working minimal examples. Therefore, the following steps show the necessary configurations for setting up an OIDC server using TLS client authentication.
The base for using TLS client authentication in the OIDC flow is to enforce mutual TLS connections. With mTls enabled, the server will always request a client certificate during the TLS handshake, which is needed for the OIDC client authentication. Add the following entries to your application.yml to enable mTLS for all connections:
server:
ssl:
client-auth: need
key-store: classpath:keystore/keystore.p12
key-store-password: changeit
trust-store: classpath:keystore/truststore.p12
trust-store-password: changeit
It is important to add the client certificate of the OIDC client to the truststore. Otherwise, the TLS connection establishment will fail before the OIDC process even starts.
The next step is to register the OIDC clients. Usually the registration can also be done in the application.yml. In this case we need to do this via a bean because we have to use the clientSettings parameter which is not available in the application.yml. To create a minimal example, the code just registers one single client:
@Bean
public RegisteredClientRepository registeredClientRepository() {
RegisteredClient registeredClient =
RegisteredClient.withId(UUID.randomUUID().toString())
.clientId("myOidcClient")
.clientAuthenticationMethod(ClientAuthenticationMethod.TLS_CLIENT_AUTH)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri(https://localhost:8080/login/oauth2/code)
.scope("openid")
.clientSettings(
ClientSettings.builder()
.x509CertificateSubjectDN("CN=myClientCert,O=myOrg,C=DE")
.build())
.build();
return new InMemoryRegisteredClientRepository(registeredClient);
}
The most obvious configuration is setting the client authentication method to TLS_CLIENT_AUTH. In addition, Spring offers a second option: SELF_SIGNED_TLS_CLIENT_AUTH. The Spring implementation considers a single received end-entity client certificate as “self-signed”, whereas a received certificate-chain is considered as regular TLS_CLIENT_AUTH. When a client just sends a single certificate during the TLS handshake, Spring will throw a very unspecific exception. In this case remember to check the received client certificate.
The most important part is to configure the ClientSettings. If the ClientSettings are empty, the server just accepts any client certificate. In this example we add the subjectDn of the client certificate to the registration. In this case the server identifies the OIDC client via the registered subjectDn value. This is the only certificate validation Spring provides. Additional validations can be added by a custom X509ClientCertificateVerfier.
While creating a Spring Boot OIDC server using TLS client authentication is quite easy, the client side needs a lot of customization. The following section shows all necessary modifications to create a Spring Boot OIDC client using TLS client authentication.
The first problem is to enable mTLS for the OIDC process. Unfortunately, Spring offers no comfortable way to configure a client certificate or modify any TLS settings for the OIDC flow. Therefore, it is necessary to create a custom mTLS client and slightly adjust the default behavior.
The first step is to configure an mTLS client with the client certificate. In this example a RestTemplate is created using Apache HttpClient 5:
@Bean
public RestTemplate restClientWithMtlsConfig() throws Exception {
SSLContext sslContext = SSLContextBuilder
.create()
.loadTrustMaterial(trustStorePath, "trustStorePass".toCharArray())
.loadKeyMaterial(keyStorePath, "keyStorePass".toCharArray(), "keypass".toCharArray())
.build();
var socketFactory = SSLConnectionSocketFactoryBuilder.create()
.setSslContext(sslContext)
.build();
var connectionManager = PoolingHttpClientConnectionManagerBuilder.create()
.setSSLSocketFactory(socketFactory)
.build();
HttpClient client = HttpClients.custom()
.setConnectionManager(connectionManager)
.build();
return new RestTemplate(new HttpComponentsClientHttpRequestFactory(client));
}
The next step is to adjust Spring’s authorization code exchange by creating the following bean:
@Bean
OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest>
oAuth2AccessTokenResponseClientWithMtls(RestClient restClientWithMtlsConfig) {
RestClientAuthorizationCodeTokenResponseClient client =
new RestClientAuthorizationCodeTokenResponseClient();
client.setRestClient(RestClient.builder(restClientWithMtlsConfig).build());
// Set custom parameters converter that supports tls_client_auth authentication method
client.setParametersConverter(
grantRequest -> {
OAuth2AuthorizationExchange authorizationExchange =
grantRequest.getAuthorizationExchange();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.set(OAuth2ParameterNames.GRANT_TYPE, grantRequest.getGrantType().getValue());
parameters.set(
OAuth2ParameterNames.CODE,
authorizationExchange.getAuthorizationResponse().getCode());
String redirectUri = authorizationExchange.getAuthorizationRequest().getRedirectUri();
if (redirectUri != null) {
parameters.set(OAuth2ParameterNames.REDIRECT_URI, redirectUri);
}
return parameters;
});
return client;
}
The bean configures the custom mTLS client to be used when exchanging the authorization code for the token. In addition, it is necessary to set a custom ParametersConverter. Using the default converter will lead to an exception because TLS client authentication as an authentication method is officially not supported.
Another custom configuration is necessary to ensure that the mTLS client is also used when refreshing a token:
@Bean
OAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest>
oAuth2RefreshTokenResponseClientWithMtls(RestClient restClientWithMtlsConfig) {
RestClientRefreshTokenTokenResponseClient client =
new RestClientRefreshTokenTokenResponseClient();
client.setRestClient(restClientWithMtlsConfig);
return client;
}
There is one last part that needs the mTLS to be configured. After receiving the token, the client calls the jwks endpoint to validate the signature. Create the following bean to use mTLS when the endpoint is called:
@Bean
JwtDecoderFactory<ClientRegistration> jwtDecoderFactory() {
return new CustomJwtDecoderFactory();
}
private class CustomJwtDecoderFactory implements JwtDecoderFactory<ClientRegistration> {
@Override
public JwtDecoder createDecoder(ClientRegistration clientRegistration) {
String jwkSetUri = clientRegistration.getProviderDetails().getJwkSetUri();
NimbusJwtDecoder jwtDecoder =
NimbusJwtDecoder.withJwkSetUri(jwkSetUri)
.restOperations(restClientWithMtlsConfig)
.build();
jwtDecoder.setClaimSetConverter(
new ClaimTypeConverter(OidcIdTokenDecoderFactory.createDefaultClaimTypeConverters()));
jwtDecoder.setJwtValidator(
new DelegatingOAuth2TokenValidator<>(
new JwtTimestampValidator(), new OidcIdTokenValidator(clientRegistration)));
return jwtDecoder;
}
}
Unfortunately, it is necessary to create a custom JWTDecoderFactory just to replace the default client. To preserve the validation logic, the original ClaimSetConverter and JwtValidator must be set.
After applying the changes above, the Spring application is capable of performing OIDC client authentication using a mTLS-secured connection to the authorization server.
In conclusion, it is possible to enable OIDC client authentication in a Spring Boot application. Although, the necessary client modifications need some effort and feel a bit hacky. Additionally, the duplicated code to preserve the original Spring configuration increases maintenance. Let’s see if Spring provides support for OIDC TLS client authentication in the future.
Nico Mattfeld is a software engineer with a focus on building Java-based backend applications. He is passionate about clean architecture and modern software engineering principles.