Spring 5 WebClient using ssl

后端 未结 3 2042
北海茫月
北海茫月 2020-12-01 02:17

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

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-01 02:40

    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();
    

提交回复
热议问题