plugins {
id 'org.springframework.boot' version "2.3.0"
id 'io.spring.dependency-management' version '1.0.9.RELEASE'
}
dependencies {
implementation('org.springframework.boot:spring-boot-starter-webflux')
}
Disable SSL verification in Spring WebClient
Upasana | July 23, 2020 | 2 min read | 2,856 views | Spring Boot 2
We can use an insecure TrustManagerFactory
that trusts all X.509 certificates without any verification. This will allow WebClient to communicate with a URL having any https certificate (self-signed, expired, wrong host, untrusted root, revoked, etc).
This code has been verified with Spring Boot 2.3.0.RELEASE
Gradle setup
You can always head to https://start.spring.io/ for creating a Spring Boot starter project.
Your build.gradle file should have spring-boot-starter-webflux
entry, as shown in below code snippet.
Spring 5 WebClient
A WebClient that uses this insecure TrustManagerFactory
can be created like shown in below code:
@Bean
public WebClient createWebClient() throws SSLException {
SslContext sslContext = SslContextBuilder
.forClient()
.trustManager(InsecureTrustManagerFactory.INSTANCE)
.build();
HttpClient httpClient = HttpClient.create().secure(t -> t.sslContext(sslContext));
return WebClient.builder().clientConnector(new ReactorClientHttpConnector(httpClient)).build();
}
Alternatively, we can build HttpClient from TcpClient, like shown below:
@Bean
public WebClient createWebClient2() throws SSLException {
SslContext sslContext = SslContextBuilder
.forClient()
.trustManager(InsecureTrustManagerFactory.INSTANCE)
.build();
TcpClient tcpClient = TcpClient.create().secure(sslContextSpec -> sslContextSpec.sslContext(sslContext));
HttpClient httpClient = HttpClient.from(tcpClient);
return WebClient.builder().clientConnector(new ReactorClientHttpConnector(httpClient)).build();
}
Now you can use this WebClient
instance to make calls to a server that has self-signed/insecure/expired certificate:
@Autowired
private WebClient webClient;
String baseUrl = "https://self-signed.badssl.com/"
public void getUrl(String baseUrl) {
webClient.get()
.uri(baseUrl)
.uri(b -> b.path("/").queryParam("name", "foo").build())
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToFlux(String.class)
.subscribe(success -> processSuccess(success, baseUrl), throwable -> processError(throwable, baseUrl));
}
Never use this TrustManagerFactory in production. It is purely for testing purposes, and thus it is very insecure. |
Top articles in this category:
- Disable SSL validation in Spring RestTemplate
- Spring Boot WebClient Basic Authentication
- Send Gupshup SMS using Java API
- Spring Webclient multipart file upload
- How does Session handling works in Servlet environment
- Prevent Lost Updates in Database Transaction using Spring Hibernate
- How to prevent duplicate form submission in Spring MVC