How to disable hostname verification in spring webclient?

前端 未结 1 1246
慢半拍i
慢半拍i 2021-01-13 11:03

I am using the spring webflux webclient tool to call the API. The API server address is HTTPS, and it is an IP address without a domain name. I need to disable the hostname

相关标签:
1条回答
  • 2021-01-13 11:19

    Aside from disabling SSL verification entirely, (WHICH I DON'T RECOMMEND) by passing in InsecureTrustManagerFactory.INSTANCE like this:

    SslContext sslContext = SslContextBuilder.forClient()
                        .keyManager(kmf)
                        .trustManager(InsecureTrustManagerFactory.INSTANCE)
                        .build();
    

    You can configure the HttpClient to essentially override the hostname verification by configuring a custom SNIMatcher as below:

    HttpClient.create().create().secure(sslContextSpec -> sslContextSpec
        .sslContext(sslContext)
        .handlerConfigurator(sslHandler -> 
            SSLEngine engine = handler.engine();
            //engine.setNeedClientAuth(true);
            SSLParameters params = new SSLParameters();
            List<SNIMatcher> matchers = new LinkedList<>();
    
            SNIMatcher matcher = new SNIMatcher(0) {
                @Override
                public boolean matches(SNIServerName serverName) {
                    return true;
                }
            };
    
            matchers.add(matcher);
            params.setSNIMatchers(matchers);
            engine.setSSLParameters(params);
    );
    

    I have tested this and verified it worked. I hope this helps!

    This was inspired by the answer here: Configure HostnameVerifier with reactor netty for spring-webflux WebClient

    0 讨论(0)
提交回复
热议问题