Skip to content

Instantly share code, notes, and snippets.

@hsg
Created December 7, 2018 14:55
Show Gist options
  • Save hsg/6152944726e46ababcf47398398b4140 to your computer and use it in GitHub Desktop.
Save hsg/6152944726e46ababcf47398398b4140 to your computer and use it in GitHub Desktop.
Client certificate authentication with Spring WebClient
public MyService(WebClient.Builder builder){
this.client = buildCustomWebClient(builder, "https://example.com");
}
private SslContext createSSLContext() {
try {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(getClass().getClassLoader().getResourceAsStream(KEYSTORE_FILE), KEYSTORE_PASSWORD.toCharArray());
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
keyManagerFactory.init(keyStore, KEYSTORE_PASSWORD.toCharArray());
return SslContextBuilder.forClient()
.keyManager(keyManagerFactory)
.build();
}
catch (Exception e) {
throw new RuntimeException("Error creating SSL context.");
}
}
private WebClient buildCustomWebClient(WebClient.Builder builder, String baseUrl){
HttpClient client = HttpClient.create().secure(spec -> spec.sslContext(createSSLContext()));
ClientHttpConnector connector = new ReactorClientHttpConnector(client);
return builder
.baseUrl(baseUrl)
.clientConnector(connector)
.build();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment