How to configure sslContext with p12 store (and password) for client authentication with https endpoint in Spring/Kotlin

Viewed 9

I want to call a https protected endpoint using a certificate and private key. I received a .p12 keystore which is protected with a password.

For testing purposes I extracted the .cer file and private key using openssl.

I could verify locally that communication works by setting the ssl context like this:

fun test(): WebClient.RequestHeadersSpec<*> {

    val sslContext = SslContextBuilder
            .forClient()
            .keyManager(ClassPathResource("cert").inputStream, ClassPathResource("key").inputStream)
            .build()

    val httpClient: HttpClient = HttpClient.create().secure { sslSpec -> sslSpec.sslContext(sslContext) }

    val webClient = WebClient
            .builder()
            .baseUrl("baseUrl")
            .clientConnector(ReactorClientHttpConnector(httpClient))
            .build()

    return webClient
            .post()
            .uri("uri")
            .contentType(MediaType.APPLICATION_JSON)
            .bodyValue("test")
}

However, I do not want to version the cert and private key in my repository. How would I set the sslContext with the .p12 keystore and the password? I did not find any examples for this scenario.

1 Answers

load file from disc

this is java but it should be easy to adapt to kotlin

KeyStore keyStore = KeyStore.getInstance("pkcs12");
keyStore.load(new FileInputStream(keyStoreLocation), keyStorePassword.toCharArray());

SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
        new SSLContextBuilder()
                .loadKeyMaterial(keyStore, keyStorePassword.toCharArray())
                .build(),
        NoopHostnameVerifier.INSTANCE);

HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();

where file location and password can provided from configuration

@Value("${keyStore.location}")
private String keyStoreLocation;

@Value("${keyStore.password}")
private String keyStorePassword;
Related