如何将客户端证书添加到Spring WebClient?

2022-04-06 00:00:00 ssl spring java spring-webflux

我正在构建一个Spring WebClient,它在内部调用托管在不同服务器上的rest API。为此,我需要向每个握手请求发送公钥(.cert)和私钥(.key)。 我不确定如何使用Spring WebClient来做到这一点。

我尝试设置WebClient,但无法添加这种轻松的代码

WebClient Builder

this.webCLient = WebClient.builder()
                .baseUrl("https://some-rest-api.com")
                .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON.toString())
                .build();

实际呼叫

this.webClient.get()
                .uri("/getData")
                .exchange()
                .flatMap(clientResponse -> {
                    System.out.println(clientResponse);
                    return clientResponse.bodyToMono(MyClass.class);
                });

由于没有证书添加到请求,我在日志中收到握手错误

javax.net.ssl.SSLException: Received fatal alert: handshake_failure
如何将这些证书添加到WebClient请求,这样我就不会收到此错误?我有证书,但不确定如何添加。


解决方案

我花了一些时间才找到托马斯答案中缺少的部分。

在这里:

public static SslContext getTwoWaySslContext() {
        
    try(FileInputStream keyStoreFileInputStream = new FileInputStream(ResourceUtils.getFile(clientSslKeyStoreClassPath));
        FileInputStream trustStoreFileInputStream = new FileInputStream(ResourceUtils.getFile(clientSslTrustStoreClassPath));   
        ) {
        KeyStore keyStore = KeyStore.getInstance("jks");
        keyStore.load(keyStoreFileInputStream, clientSslKeyStorePassword.toCharArray());
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
        keyManagerFactory.init(keyStore, clientSslKeyStorePassword.toCharArray());
            
        KeyStore trustStore = KeyStore.getInstance("jks");
        trustStore.load(trustStoreFileInputStream, clientSslTrustStorePassword.toCharArray());
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
        trustManagerFactory.init(trustStore);
            
        return SslContextBuilder.forClient()
            .keyManager(keyManagerFactory)
            .trustManager(trustManagerFactory)
            .build();
            
    } catch (Exception e) {
        log.error("An error has occurred: ", e);
    }
        
    return null;
}


HttpClient httpClient = HttpClient.create().secure(sslSpec -> sslSpec.sslContext(SslUtil.getTwoWaySslContext()));
ClientHttpConnector clientHttpConnector = new ReactorClientHttpConnector(httpClient);
WebClient webClient = webClientBuilder
    .clientConnector(clientHttpConnector)
    .baseUrl(baseUrl)
    .build();

尽情享受!

相关文章