Apache HTTP 客户端 loadTrustMaterial 不起作用
Posted
技术标签:
【中文标题】Apache HTTP 客户端 loadTrustMaterial 不起作用【英文标题】:Apache HTTP Client loadTrustMaterial not working 【发布时间】:2021-04-12 00:37:16 【问题描述】:首先,源代码中没有注释。
org.apache.hc.core5.ssl.SSLContextBuilder#loadTrustMaterial(org.apache.hc.core5.ssl.TrustStrategy)
public SSLContextBuilder loadTrustMaterial(
final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException
return loadTrustMaterial(null, trustStrategy);
这里是触发混淆行为的代码,和apache官方demoApache Demo一样
@Test
void customStrategy() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException, IOException, ParseException
SSLContextBuilder sslContextBuilder = SSLContexts.custom();
sslContextBuilder.loadTrustMaterial((chain, authType) -> false);
SSLContext sslcontext = sslContextBuilder.build();
SSLConnectionSocketFactoryBuilder sslConnectionSocketFactoryBuilder = SSLConnectionSocketFactoryBuilder.create();
sslConnectionSocketFactoryBuilder.setSslContext(sslcontext);
sslConnectionSocketFactoryBuilder.setTlsVersions(TLS.V_1_2);
SSLConnectionSocketFactory sslConnectionSocketFactory = sslConnectionSocketFactoryBuilder.build();
PoolingHttpClientConnectionManagerBuilder poolingHttpClientConnectionManagerBuilder = PoolingHttpClientConnectionManagerBuilder.create();
poolingHttpClientConnectionManagerBuilder.setSSLSocketFactory(sslConnectionSocketFactory);
HttpClientConnectionManager httpClientConnectionManager = poolingHttpClientConnectionManagerBuilder.build();
HttpClientBuilder httpClientBuilder = HttpClients.custom();
httpClientBuilder.setConnectionManager(httpClientConnectionManager);
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
HttpClientContext clientContext = HttpClientContext.create();
CloseableHttpResponse response = closeableHttpClient.execute(new HttpGet("https://www.baidu.com"), clientContext);
System.out.println("BODY-Length " + EntityUtils.toString(response.getEntity()).length());
SSLSession sslSession = clientContext.getSSLSession();
System.out.println(sslSession.getPeerHost() + ":" + sslSession.getPeerPort());
输出是:
... ...
BODY-Length 2443
www.baidu.com:443
即使我在自定义 TrustStrategy 中直接返回 false
。
sslContextBuilder.loadTrustMaterial((chain, authType) ->
throw new CertificateException();
);
那会中断连接,但是我不认为如果接口返回false,而是只有在异常正确使用时才中断。
问题: 为什么 return false 不起作用? Thorw execption 让我感觉不对劲,这是为了设计吗?
【问题讨论】:
【参考方案1】:请参阅TrustStrategy#isTrusted
的 javadocs。如果 TrustStrategy
从 isTrusted
方法返回 false,则证书验证由 SSL 上下文中配置的信任管理器执行。
【讨论】:
以上是关于Apache HTTP 客户端 loadTrustMaterial 不起作用的主要内容,如果未能解决你的问题,请参考以下文章
Apache HTTP 客户端 loadTrustMaterial 不起作用