Self Signed Certificate in Spring 5 WebClient

Carvia Tech | November 23, 2019 | 1 min read | 1,587 views | Spring Boot 2


We can use an insecure TrustManagerFactory that trusts all X.509 certificates without any verification. This will allow any https certificate (self-signed, expired, etc) with WebClient communication.

A WebClient that uses this insecure TrustManagerFactory can be created like shown in below code:

Creating WebClient Bean
@Bean
public WebClient createWebClient() throws SSLException {
    SslContext sslContext = SslContextBuilder
            .forClient()
            .trustManager(InsecureTrustManagerFactory.INSTANCE)
            .build();
    ClientHttpConnector httpConnector = new ReactorClientHttpConnector(opt -> opt.sslContext(sslContext));
    return WebClient.builder(). clientConnector(httpConnector).build();
}

Now you can use this WebClient instance to make calls to a server that has self-signed certificate:

Making Call
public void getUrl(String baseUrl) {
    webClient.get()
        .uri(baseUrl)
        .uri(b -> b.path("/").queryParam("name", "foo").build())
        .accept(MediaType.APPLICATION_JSON)
        .retrieve()
        .bodyToFlux(Health.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:
  1. Disable SSL certificate validation in RestTemplate
  2. Spring Boot file upload with Kotlin and Junit 5
  3. Testing web layer in Spring Boot using WebMvcTest
  4. SendGrid emails with Spring Boot and Java
  5. What is new in Spring Boot 2
  6. Setting a Random Port in Spring Boot Application at startup
  7. How to prevent duplicate form submission in Spring MVC



Find more on this topic:
Spring Framework image
Spring Framework

Spring Framework - MVC, Dependency Injection, Spring Hibernate, Spring Data JPA, Spring Boot and Spring Cloud for Microservices Architecture.

Last updated 1 week ago


Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info