WebClient获取SSL/TLS证书



java.net在其API中有一个简单的getServerCertificates(示例如下)。我正在寻找一个类似的操作反应器-netty,如果没有,在任何其他响应式API的spring-boot/webflux/HttpClient。

此操作(客户端读取证书)在reactor-netty中似乎不可能。是吗?如果不是,在另一个弹簧引导组件中是否有替代方法来完成此操作?

package com.example.readCertificate.service;
import java.net.URL;
import java.securiiity.cert.Certificate;
import javax.net.ssl.HttpsURLConnection;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class ShowCert {
private Logger logger = LogManager.getLogger();
public void showCert(String url) {
try {
URL destinationURL = new URL(url);
HttpsURLConnection connection = (HttpsURLConnection) destinationURL.openConnection();
connection.connect();
Certificate[] certificates = connection.getServerCertificates();
for (Certificate certificate : certificates) {
logger.info("certificate is:" + certificate);
}
} catch (Exception e) {
logger.error(e);
}
}
}

在Spring WebFlux的WebClient中,我们通常使用netty作为后端。我们提供了一个beanReactorClientHttpConnector,我们在其中创建netty http-client。

用于处理SSL netty在通道管道中使用处理程序。

在这里,我将回调事件doOnConnected()并访问SSL处理程序和SSLSession

SSLSession提供了getPeerCertificates(), getLocalCertificates()方法,因此我们可以在这里访问证书。

@Bean
public ReactorClientHttpConnector reactorClientHttpConnector() {
return new ReactorClientHttpConnector(
HttpClient.create()
.doOnConnected(connection -> {
ChannelPipeline pipeline = connection.channel().pipeline();

Optional.ofNullable(pipeline)
.map(p -> p.get(SslHandler.class))
.map(SslHandler::engine)
.map(SSLEngine::getSession)
.ifPresent(sslSession -> {
try {
Certificate[] peerCertificates = sslSession.getPeerCertificates();
if (Objects.nonNull(peerCertificates)) {
Stream.of(peerCertificates)
.forEach(System.out::println);
}
} catch (Exception e) {
e.printStackTrace();
}
});
})
);
}

创建WebClient:

@Bean
public WebClient httpsClient() {
return WebClient.builder()
.clientConnector(reactorClientHttpConnector())
.baseUrl("https://secured-resource.com)
.build();
}

然后,当使用这个httpsClient bean进行http-call时,您应该在控制台中看到结果

最新更新