Apache HTTP 客户端 loadTrustMaterial 不工作

Apache HTTP Client loadTrustMaterial not working

首先,源代码中没有注释。

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官方demo一样Apache 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 中直接 return false

sslContextBuilder.loadTrustMaterial((chain, authType) -> {
    throw new CertificateException();
});

那会中断连接,但我不认为如果接口 return false,但只有在异常正确使用时才中断。

问题: 为什么 return false 不起作用? Thorw execption让我感觉不对,这是设计的吗?

请参阅 TrustStrategy#isTrusted 的 javadoc。如果来自 isTrusted 方法的 TrustStrategy returns 为假,则证书验证由在 SSL 上下文中配置的信任管理器执行。