Created
September 18, 2020 06:41
-
-
Save jvorhauer/0141f4a2ea10f76ad485afe1fdab048f to your computer and use it in GitHub Desktop.
WebClient with SSL and basic authentication
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
// 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