首页 > 解决方案 > 使用 reactor netty 为 spring-webflux WebClient 配置 HostnameVerifier

问题描述

我正在尝试使用 ssl 和客户端主机名验证配置 spring-webflux WebClient(在引擎盖下使用反应器网络)。我提供了 javax.net.ssl.SSLContext、HostnameVerifier 和受信任主机名列表(作为字符串列表)。

到目前为止,我已经使用 SSLContext 配置了 WebClient,但我找不到配置主机名验证的方法。

陈述我的问题:我有一组受信任的服务主机名(字符串列表)和一个 HostnameVerifier。我想用它配置我的 WebClient。

有没有可能用 javax.net.ssl.HostnameVerifier 做到这一点?反应堆网络中有替代方法吗?

这是我到目前为止所得到的:

WebClient.builder()
  .clientConnector(
    new ReactorClientHttpConnector(
      opt -> opt.sslContext(new JdkSslContext(mySSLContext, 
                      true, ClientAuth.OPTIONAL))))
  .build();

标签: javasslhttpsspring-webfluxreactor-netty

解决方案


您应该提供有效的证书颁发机构证书 ( trustManager()) 和可选的用户证书以及用于授权的私钥和私钥密码 ( keyManager())。您的服务 SSL 证书应该由您在 trustManager() 中定义的同一 CA 签名。

使用服务主机名自动验证主机名。如果没有匹配java.security.cert.CertificateException: No subject alternative names present异常将被抛出。实际上我找不到省略主机名验证的方法(不通过 using 省略整个 SSL 证书验证 .trustManager(InsecureTrustManagerFactory.INSTANCE))。

我已经在本地测试了这个解决方案。我的 web 服务在我的本地机器上运行,但它的 SSL 证书只包含 DNS 名称,而不是 IP 地址。因此,出于调试目的,我在 hosts 文件中添加了条目,并将我的服务 IP 映射到正确的 DNS 名称。

SslContext sslContext = SslContextBuilder
        .forClient()
        .trustManager(new FileInputStream(caPath))
        .keyManager(
                new FileInputStream(userCertPath),
                new FileInputStream(userPrivateKeyPath),
                userPrivateKeyPassword
        )
        .build();

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

WebClient webClient = WebClient.builder()
        .clientConnector(new ReactorClientHttpConnector(httpClient))
        .build();

推荐阅读