SpringBoot项目配置HTTPS接口的安全访问(openssl配置)

参考:

https://blog.youkuaiyun.com/weixin_45355769/article/details/131727935

安装好openssl后,

创建 D:\certificate

CA文件夹下包含:

  • index.txt OpenSSL在创建自签证书时会向该文件里写下索引
  • database.txt OpenSSL会模拟数据库将一些敏感信息写在该文件里
  • serial 创建该文件后,请编辑在第一行写下 01 (注意,没有后缀)
  • newcerts 文件夹

注意: 这里提到的所有文件必须补齐,并且文件名不得更改 !
再注:在windows,没有openssl.conf默认文件夹的位置,所以需要自己配置环境变量。

1.3 生成自己的CA证书
首先,我们需要把自己先扮演成CA机构,根据非对称加密的概念,我们需要有一对密钥,对应一把公钥和一把私钥,私钥放在自己身边,公钥提供出去,这边需要注意的是不能把他看成是服务端,CA机构是在客户端和服务端两者之间的一个存在,这边理解了后,我们先来创建一把私钥,可以使用openssl来生成。

1.3.1 生成 rootca.key私钥文件

openssl genrsa -out rootca.key 4096

1.3.2 根据私钥文件生成req请求文件,req请求文件用来生成证书的时候使用

如果是自己使用,搭建着玩或者自己私人的网站,就使用openssl生成就好了。

1.3.3 生成X.509格式的CA根证书rootca.crt

openssl x509 -req -in rootca.csr -out rootca.crt -signkey rootca.key -days 3650

<think>我们正在解决Spring Boot应用中使用HttpClient发起HTTPS POST请求时的证书信任问题。当目标服务器使用自签名证书或证书链不完整时,Java会抛出`unable to find valid certification path to requested target`异常。下面提供两种解决方案:全局信任证书(修改JVM信任库)和局部信任证书(在HttpClient中忽略证书验证)。根据安全要求和场景选择。 ### 方法1:导入服务器证书到JVM信任库(推荐) 此方法将目标服务器的证书导入Java的全局信任库(cacerts),适用于所有使用该JVM的应用程序。 #### 步骤: 1. **导出服务器证书**(使用OpenSSL): ```bash openssl s_client -connect your-server.com:443 -showcerts </dev/null 2>/dev/null | openssl x509 -outform PEM > server.crt ``` 2. **导入证书到JVM信任库**: ```bash # 查找Java安装路径(Spring Boot应用使用的JRE) # 示例路径(根据实际调整): JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64 keytool -importcert -alias server_cert -file server.crt -keystore "$JAVA_HOME/lib/security/cacerts" -storepass changeit ``` 出现提示时输入`yes`确认信任。 3. **重启Spring Boot应用**: 确保应用使用更新后的信任库。 ### 方法2:在HttpClient中绕过证书验证(仅开发环境) 此方法通过自定义`HttpClient`忽略SSL证书验证,**仅建议用于开发或测试环境**。 #### 示例代码(使用Apache HttpClient): ```java import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.TrustStrategy; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContexts; import javax.net.ssl.SSLContext; import java.security.cert.X509Certificate; public CloseableHttpClient createInsecureHttpClient() throws Exception { // 信任所有证书(危险!) TrustStrategy trustAll = (X509Certificate[] chain, String authType) -> true; SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(null, trustAll) .build(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext); return HttpClients.custom() .setSSLSocketFactory(socketFactory) .build(); } ``` #### 使用示例: ```java try (CloseableHttpClient httpClient = createInsecureHttpClient()) { HttpPost httpPost = new HttpPost("https://your-server.com/api"); // 设置请求体等... HttpResponse response = httpClient.execute(httpPost); // 处理响应... } ``` ### 安全建议 - 生产环境必须使用方法1(导入证书),避免信任所有证书带来的安全风险[^1]。 - 如果服务器使用公开CA签发的证书,通常无需额外配置(JVM默认信任常见CA)。 ### 相关问题 1. 如何在Spring Boot中配置多个HTTPS证书? 2. 使用RestTemplate时如何忽略SSL证书验证? 3. 如何为Spring Boot应用生成自签名证书? [^1]: The basic auth credentials for the/tokenendpoint are theclient-idandclient-secret. The user credentials are the normal Spring Security user details (which default in Spring Boot to “user” and a random password). [^2]: 格式: logging.level.*= # Log levels severity mapping. For instance `logging.level.org.springframework=DEBUG` Spring Boot的自动配置的原理。 [^3]: INFO 6188 --- [ main] c.i.springboot.demo.HelloApplication : Started HelloApplication in 3.281 seconds (JVM running for 3.601) 4.3.6. 测试。</think>在 Spring Boot 应用中,使用 `HttpClient` 访问 HTTPS 接口时遇到证书信任问题(如 `unable to find valid certification path to requested target`),可通过以下方法解决。根据安全需求选择方案: --- ### 方案 1:导入证书到 JVM 信任库(推荐生产环境) 此方法将目标服务器的证书添加到 JVM 全局信任库(`cacerts`),适用于所有应用。 #### 步骤: 1. **导出目标服务器证书**(替换 `your-server.com:443`): ```bash openssl s_client -connect your-server.com:443 -showcerts </dev/null | \ openssl x509 -outform PEM > server.crt ``` 2. **导入证书到 Java 信任库**: ```bash # 查找 Java 安装路径(Spring Boot 使用的 JRE) # 示例路径(根据实际调整): JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64 keytool -importcert \ -alias server_cert \ -file server.crt \ -keystore "$JAVA_HOME/lib/security/cacerts" \ -storepass changeit # 默认密码 ``` ✔️ 提示时输入 `yes` 确认信任 3. **重启 Spring Boot 应用** --- ### 方案 2:自定义 HttpClient 忽略证书验证(仅限开发环境) 通过自定义 `HttpClient` 跳过证书检查(**不推荐生产环境使用**)。 #### 示例代码: ```java import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.TrustStrategy; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContexts; import javax.net.ssl.SSLContext; public CloseableHttpClient createInsecureHttpClient() throws Exception { // 信任所有证书(危险!) TrustStrategy trustAll = (chain, authType) -> true; SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(null, trustAll) .build(); return HttpClients.custom() .setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext)) .build(); } ``` #### 使用示例: ```java try (CloseableHttpClient httpClient = createInsecureHttpClient()) { HttpPost post = new HttpPost("https://your-api.com/endpoint"); // 添加请求体等配置... HttpResponse response = httpClient.execute(post); } ``` --- ### 方案 3:通过配置信任特定证书(生产安全方案) 创建自定义信任库仅信任目标证书: 1. **创建新信任库**: ```bash keytool -import -file server.crt -alias mycert -keystore custom-truststore.jks -storepass mypassword ``` 2. **在 `application.properties` 中配置**: ```properties # 指定自定义信任库 server.ssl.trust-store=classpath:custom-truststore.jks server.ssl.trust-store-password=mypassword ``` --- ### 验证是否生效 在 `application.properties` 中启用 SSL 调试日志: ```properties logging.level.org.apache.http=DEBUG logging.level.org.springframework.web=DEBUG ``` 观察日志中是否仍有 `PKIX path building failed` 错误[^2][^3]。 --- ### 关键区别 | 方案 | 安全级别 | 影响范围 | 适用场景 | |---------------------|----------|----------------|------------------| | 导入 JVM 信任库 | 高 | 全局 | 生产环境 | | 自定义 HttpClient | 低 | 当前应用 | 开发/测试 | | 自定义信任库 | 中高 | 当前应用 | 生产环境(推荐) | --- ### 相关问题 1. 如何在 Spring Boot 中为 RestTemplate 配置 SSL 证书? 2. 使用自签名证书时如何避免 RestTemplate 的 SSL 错误? 3. Spring Boot 中如何动态加载多个 HTTPS 证书? 4. 如何为 Spring Cloud 微服务配置双向 SSL 认证? 5. HttpClient 和 RestTemplate 在 SSL 处理上有何区别? [^1]: The basic auth credentials for the/tokenendpoint are theclient-idandclient-secret. The user credentials are the normal Spring Security user details (which default in Spring Boot to "user" and a random password). [^2]: 格式: logging.level.*= # Log levels severity mapping. For instance `logging.level.org.springframework=DEBUG` Spring Boot的自动配置的原理。 [^3]: INFO 6188 --- [ main] c.i.springboot.demo.HelloApplication : Started HelloApplication in 3.281 seconds (JVM running for 3.601) 4.3.6. 测试。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值