Spring 启动 WebCLient 接受自签名证书,但不接受 InsecureTrustManagerFactory

Spring Boot WebCLient accept Self Signed Certificate, but not with InsecureTrustManagerFactory

我正在尝试使用 Spring 引导构建 REST 客户端并利用 WebClient,但是在尝试配置对 REST API 的 HTTPS 调用时我遇到了冲突。 =19=]

当使用 RestTemplate 时,我能够通过使用 TrustSelfSignedStrategy() 获得自签名证书,因此即使证书是自签名的,它仍在验证其主机名、到期日期等

WebClient中,到目前为止我只找到了利用InsecureTrustManagerFactory自签名证书的方式,但是这也会导致整个验证被跳过,有效地使使用的目的无效首先是 HTTPS。

引自Netty documentations

An insecure TrustManagerFactory that trusts all X.509 certificates without any verification.

NOTE: Never use this TrustManagerFactory in production. It is purely for testing purposes, and thus it is very insecure.

有什么方法可以在 WebClient 中使用自签名证书而不必取消所有验证?

是的,您可以使用自签名证书。您需要做的是将自签名证书添加到 java 密钥库中,然后通过获取密钥库并将其转换为 TrustManager 将其加载到您的应用程序中。后记,您可以将 TrustManager 提供给 SslContextBuilder,这是配置基于 Netty 的 WebClient 所需的。请参阅下面的示例:

Path truststorePath = Paths.get(/path/to/your/truststore)
InputStream truststoreInputStream = Files.newInputStream(truststorePath, StandardOpenOption.READ)

KeyStore truststore = KeyStore.getInstance(KeyStore.getDefaultType());
truststore.load(truststoreInputStream, truststorePassword);

TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(truststore);

SslContext sslContext = SslContextBuilder.forClient()
        .trustManager(trustManagerFactory)
        .build()

HttpClient httpClient = HttpClient.create()
        .secure(sslSpec -> sslSpec.sslContext(sslContext));

WebClient.builder()
        .clientConnector(new ReactorClientHttpConnector(httpClient))
        .build()