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



我正在尝试使用Spring Boot并使用WebClient构建REST客户端,但当我尝试配置对REST API的HTTPS调用时,我遇到了冲突。

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

WebClient中,到目前为止,我只发现了使用InsecureTrustManagerFactory的自签名证书的方式,但这也会导致整个验证被跳过,实际上从一开始就没有使用HTTPS的目的。

引用自Netty文件:

一个不安全的TrustManagerFactory,它在没有任何验证的情况下信任所有X.509证书。

注意:切勿在生产中使用此TrustManagerFactory。它纯粹是为了测试目的,因此非常不安全。

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

是的,您可以使用自签名证书。您需要做的是将自签名证书添加到java密钥库中,并通过获取密钥库并将其转换为TrustManager将其加载到应用程序中。事后,您可以将TrustManager提供给SslContext Builder,这是配置基于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()

最新更新