How to add client certificates to the Spring WebClient?(如何将客户端证书添加到Spring WebClient?)
本文介绍了如何将客户端证书添加到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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:如何将客户端证书添加到Spring WebClient?
基础教程推荐
猜你喜欢
- 不推荐使用 Api 注释的描述 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 大摇大摆的枚举 2022-01-01
