Created
December 7, 2018 14:55
-
-
Save hsg/6152944726e46ababcf47398398b4140 to your computer and use it in GitHub Desktop.
Client certificate authentication with Spring WebClient
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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