Self Signed Certificate in Spring 5 WebClient

Carvia Tech | May 05, 2019 at 01:19 PM | 335 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. What is new in Spring Boot 2
  2. Setting a Random Port in Spring Boot Application at startup
  3. How to prevent duplicate form submission in Spring MVC
  4. Spring Boot 2.0 Reactive Web Performance Metrics
  5. What are different Bean Scopes in Spring?
  6. Running Spring Boot app as a service in unix
  7. Run method on application startup in Spring Boot


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 month ago


Recommended books for interview preparation:
You may also be interested in..
Generic placeholder image
ebook PDF - Cracking Spring Microservices Interviews for Java Developers
You may also be interested in..
Generic placeholder image
ebook PDF - Cracking Java Interviews v3.5 by Munish Chandel
You may also be interested in..
Generic placeholder image
ebook PDF - Cracking Spring Microservices Interviews for Java Developers
You may also be interested in..
Generic placeholder image
ebook PDF - Cracking Java Interviews v3.5 by Munish Chandel
Facebook Page
Free Email Updates

Enter your email address to subscribe to this blog and receive notifications of new posts by email.


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