如何将客户端证书添加到Spring WebClient? [英] How to add client certificates to the Spring WebClient?

查看:23
本文介绍了如何将客户端证书添加到Spring WebClient?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个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();

尽情享受!

这篇关于如何将客户端证书添加到Spring WebClient?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆