Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring 5 WebClient using ssl

I'm trying to find examples of WebClient use.

My goal is to use Spring 5 WebClient to query a REST service using https and self signed certificate

Any example?

like image 614
Seb Avatar asked Jul 31 '17 14:07

Seb


1 Answers

Looks like Spring 5.1.1 (Spring boot 2.1.0) removed HttpClientOptions from ReactorClientHttpConnector, so you can not configure options while creating instance of ReactorClientHttpConnector

One option that works now is:

val sslContext = SslContextBuilder             .forClient()             .trustManager(InsecureTrustManagerFactory.INSTANCE)             .build() val httpClient = HttpClient.create().secure { t -> t.sslContext(sslContext) } val webClient = WebClient.builder().clientConnector(ReactorClientHttpConnector(httpClient)).build() 

Basically while creating the HttpClient, we are configuring the insecure sslContext, and then passing this httpClient for use in ReactorClientHttpConnector globally.

The other option is to configure TcpClient with insecure sslContext and use it to create HttpClient instance, as illustrated below:

val sslContext = SslContextBuilder             .forClient()             .trustManager(InsecureTrustManagerFactory.INSTANCE)             .build() val tcpClient = TcpClient.create().secure { sslProviderBuilder -> sslProviderBuilder.sslContext(sslContext) } val httpClient = HttpClient.from(tcpClient) val webClient =  WebClient.builder().clientConnector(ReactorClientHttpConnector(httpClient)).build() 

For more information:

  • https://docs.spring.io/spring/docs/5.1.1.RELEASE/spring-framework-reference/web-reactive.html#webflux-client-builder-reactor
  • https://netty.io/4.0/api/io/netty/handler/ssl/util/InsecureTrustManagerFactory.html

Update: Java version of the same code

SslContext context = SslContextBuilder.forClient()     .trustManager(InsecureTrustManagerFactory.INSTANCE)     .build();                  HttpClient httpClient = HttpClient.create().secure(t -> t.sslContext(context));  WebClient wc = WebClient                     .builder()                     .clientConnector(new ReactorClientHttpConnector(httpClient)).build(); 
like image 122
Munish Chandel Avatar answered Sep 30 '22 08:09

Munish Chandel