Skip to content

Instantly share code, notes, and snippets.

@likhoman
Created June 27, 2020 08:06
Show Gist options
  • Save likhoman/8d74401112b6972fad32953a93d36218 to your computer and use it in GitHub Desktop.
Save likhoman/8d74401112b6972fad32953a93d36218 to your computer and use it in GitHub Desktop.
package org.github.likhoman.mtls.client;
import io.netty.handler.ssl.SslContext;
import nl.altindag.sslcontext.SSLFactory;
import nl.altindag.sslcontext.util.NettySslContextUtils;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.reactive.function.client.WebClient;
import javax.net.ssl.SSLException;
import static java.util.Objects.nonNull;
@Configuration
public class MtlsHttpClient {
@Bean
@Scope("prototype")
public SSLFactory sslFactory(
@Value("${client.ssl.key-store:}") String keyStorePath,
@Value("${client.ssl.key-store-password:}") char[] keyStorePassword,
@Value("${client.ssl.trust-store:}") String trustStorePath,
@Value("${client.ssl.trust-store-password:}") char[] trustStorePassword) {
SSLFactory.Builder sslFactoryBuilder = SSLFactory.builder()
.withHostnameVerifier(new DefaultHostnameVerifier())
.withProtocol("TLSv1.3")
.withIdentity(keyStorePath, keyStorePassword)
.withTrustStore(trustStorePath, trustStorePassword);
return sslFactoryBuilder.build();
}
@Bean
@Scope("prototype")
public reactor.netty.http.client.HttpClient nettyHttpClient(@Autowired(required = false) SSLFactory sslFactory) throws SSLException {
reactor.netty.http.client.HttpClient httpClient = reactor.netty.http.client.HttpClient.create();
if (nonNull(sslFactory)) {
SslContext sslContext = NettySslContextUtils.forClient(sslFactory).build();
httpClient = httpClient.secure(sslSpec -> sslSpec.sslContext(sslContext));
}
return httpClient;
}
@Bean
public WebClient webClient(reactor.netty.http.client.HttpClient httpClient) {
return WebClient.builder()
.clientConnector(new ReactorClientHttpConnector(httpClient))
.build();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment