【问题标题】:Spring Boot WebCLient accept Self Signed Certificate, but not with InsecureTrustManagerFactorySpring Boot WebCLient 接受自签名证书,但不接受 InsecureTrustManagerFactory
【发布时间】:2021-03-23 08:08:23
【问题描述】:

我正在尝试使用 Spring Boot 和 WebClient 构建一个 REST 客户端,但是在尝试配置 HTTPS 调用到 REST API 时我遇到了冲突。

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

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

引用自Netty documentations:

一个不安全的 TrustManagerFactory,它信任所有 X.509 证书而无需任何验证。

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

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

【问题讨论】:

    标签: spring-boot ssl https reactive-programming reactor-netty


    【解决方案1】:

    是的,您可以使用自签名证书。您需要做的是将自签名证书添加到 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()
    

    【讨论】:

    • 我认为这种方法仍然强制执行所有其他验证;主机名,到期日等?我记得更改为InsecureTrustManagerFactory,因为这似乎无法使用自签名;但是经过一些思考,这可能是由其他原因引起的。当我再试一次时,我会回来的。谢谢顺便说一句!
    • 有点奇怪;这是由于证书没有正确准备(主机名和 CN 不匹配 - 因此错过了我这个问题的全部目的),所以我在开发环境中连接它有一些困难。我正在尝试使用更合适的证书在 pre-prod 环境中进行测试,希望是今天,因为我从昨天开始请求访问
    • 结果刚刚进来;有用。我会将此标记为已接受的答案,非常感谢!
    猜你喜欢
    • 2015-12-25
    • 2021-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多