Skip to content

Instantly share code, notes, and snippets.

@jvorhauer
Created September 18, 2020 06:41
Show Gist options
  • Save jvorhauer/0141f4a2ea10f76ad485afe1fdab048f to your computer and use it in GitHub Desktop.
Save jvorhauer/0141f4a2ea10f76ad485afe1fdab048f to your computer and use it in GitHub Desktop.
WebClient with SSL and basic authentication
// https://www.viralpatel.net/basic-authentication-spring-webclient/
@Bean
public WebClient webClient() {
var httpClient = trustStore == null || trustStore.isEmpty() ?
reactor.netty.http.client.HttpClient.create().compress(true) :
reactor.netty.http.client.HttpClient.create().compress(true)
.secure(sslCtxSpec -> sslCtxSpec.sslContext(createSslContext()));
return WebClient.builder()
.baseUrl(baseUrl)
.defaultHeaders(header -> header.setBasicAuth(username, password))
.clientConnector(new ReactorClientHttpConnector(httpClient))
.build();
}
@Bean
public SslContext createSslContext() {
final byte[] certificate = Base64.getDecoder().decode(trustStore);
final ByteArrayInputStream bais = new ByteArrayInputStream(certificate);
try {
final KeyStore ks = KeyStore.getInstance("pkcs12");
ks.load(bais, trustPassword.toCharArray());
final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, trustPassword.toCharArray());
return SslContextBuilder.forClient().keyManager(kmf).build();
} catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException | UnrecoverableKeyException e) {
log.error("createSslContext: {}", e.getMessage());
throw new PlotSecurityException(e);
}
}
public static final class PlotSecurityException extends RuntimeException {
public PlotSecurityException(final Exception e) {
super(e);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment