当前位置: 首页 > news >正文

Apache HttpClient 4和5访问没有有效证书的HTTPS

本文将展示如何配置Apache HttpClient 4和5以支持“接受所有”SSL。

目标很简单——访问没有有效证书的HTTPS URL。

SSLPeerUnverifiedException

在未配置SSL的情况下,尝试消费一个HTTPS URL时会遇到以下测试失败:

@Test
void whenHttpsUrlIsConsumed_thenException() {String urlOverHttps = "https://localhost:8082/httpclient-simple";HttpGet getMethod = new HttpGet(urlOverHttps);assertThrows(SSLPeerUnverifiedException.class, () -> {CloseableHttpClient httpClient = HttpClients.createDefault();HttpResponse response = httpClient.execute(getMethod, new CustomHttpClientResponseHandler());assertThat(response.getCode(), equalTo(200));});
}

具体的失败信息是:

javax.net.ssl.SSLPeerUnverifiedException: peer not authenticatedat sun.security.ssl.SSLSessionImpl.getPeerCertificates(SSLSessionImpl.java:397)at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:126)...

当无法为URL建立有效的信任链时,就会抛出javax.net.ssl.SSLPeerUnverifiedException异常。

配置SSL - 接受所有(HttpClient 5)

现在让我们配置HTTP客户端以信任所有证书链,无论其有效性如何:

@Test
void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenOk() throws GeneralSecurityException, IOException {final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);final TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create().register("https", sslsf).register("http", new PlainConnectionSocketFactory()).build();final BasicHttpClientConnectionManager connectionManager =new BasicHttpClientConnectionManager(socketFactoryRegistry);try (CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).build();CloseableHttpResponse response = (CloseableHttpResponse) httpClient.execute(getMethod, new CustomHttpClientResponseHandler())) {final int statusCode = response.getCode();assertThat(statusCode, equalTo(HttpStatus.SC_OK));}
}

通过新的TrustStrategy覆盖标准证书验证过程后,测试现在可以通过,客户端能够成功消费HTTPS URL。

配置SSL - 接受所有(HttpClient 4.5)

对于HttpClient 4.5版本,配置方式类似,但使用了一些不同的API:

@Test
public final void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenOk()throws GeneralSecurityException {TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create().register("https", sslsf).register("http", new PlainConnectionSocketFactory()).build();BasicHttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(socketFactoryRegistry);CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).setConnectionManager(connectionManager).build();HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);ResponseEntity<String> response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class);assertThat(response.getStatusCode().value(), equalTo(200));
}

Spring RestTemplate与SSL(HttpClient 5)

了解了如何配置带有SSL支持的基本HttpClient之后,我们来看看更高级别的客户端——Spring RestTemplate

在没有配置SSL的情况下,预期的测试会失败:

@Test
void whenHttpsUrlIsConsumed_thenException() {final String urlOverHttps = "https://localhost:8443/httpclient-simple/api/bars/1";assertThrows(ResourceAccessException.class, () -> {final ResponseEntity<String> response = new RestTemplate().exchange(urlOverHttps, HttpMethod.GET, null, String.class);assertThat(response.getStatusCode().value(), equalTo(200));});
}

接下来,配置SSL来解决这个问题:

@Test
void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenOk() throws GeneralSecurityException {final TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create().register("https", sslsf).register("http", new PlainConnectionSocketFactory()).build();final BasicHttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(socketFactoryRegistry);final CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).build();final HttpComponentsClientHttpRequestFactory requestFactory =new HttpComponentsClientHttpRequestFactory(httpClient);final ResponseEntity<String> response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class);assertThat(response.getStatusCode().value(), equalTo(200));
}

这里配置方式与直接使用HttpClient非常相似,我们用带有SSL支持的请求工厂配置了RestTemplate

结论

本教程讨论了如何配置Apache HttpClient以使其能够消费任何HTTPS URL,无论证书的有效性如何。

同样也展示了如何对Spring RestTemplate进行同样的配置。

重要的是要理解这种策略完全忽略了证书检查——这使得它不安全,仅应在合理的情况下使用。

http://www.lryc.cn/news/498031.html

相关文章:

  • Lighthouse(灯塔)—— Chrome 浏览器性能测试工具
  • 扫二维码进小程序的指定页面
  • 如何用IntelliJ IDEA开发Android Studio用自定义Gradle插件
  • YOLOv8实战道路裂缝缺陷识别
  • RPC一分钟
  • Elasticsearch ILM 故障排除:常见问题及修复
  • Unity 设计模式-策略模式(Strategy Pattern)详解
  • 【Maven系列】深入解析 Maven 常用命令
  • 微信小程序之简单的数据中心管理平台(1)
  • sqlmap --os-shell的原理(MySQL,MSSQL,PostgreSQL,Oracle,SQLite)
  • 2024年认证杯SPSSPRO杯数学建模C题(第一阶段)云中的海盐解题全过程文档及程序
  • 三维扫描检测在汽车制造中的应用
  • 【NoSQL数据库】Hbase基本操作——数据库表的增删改查
  • 【C++】格式化输出详解:掌握 cout 的进阶用法
  • 设计模式学习思路二
  • 什么是等级保护
  • k8s api对象,CRD
  • 【C++指南】C++内存管理 深度解析
  • C++小碗菜之二:软件单元测试
  • PyCharm+Selenium+Pytest配置小记
  • 摩尔线程 国产显卡 MUSA 并行编程 学习笔记-2024/12/04
  • 【FAQ】HarmonyOS SDK 闭源开放能力 —Remote Communication Kit
  • 【日常记录-Mybatis】PageHelper导致语句截断
  • 随时随地掌控数据:如何使用手机APP远程访问飞牛云NAS
  • JVM 类加载器有哪些?双亲委派机制的作用是什么?如何自定义类加载器?
  • 从基态到激发态再到里德伯态的双光子激发过程
  • Clickhouse 外部存储引擎
  • eclipse怎么配置jdk路径?
  • 【前端】JavaScript 中的创建对象模式要点
  • GWAS分析先做后学