springboot项目如何从http变成接收https,已申请了CA颁布的ssl证书
时间: 2025-01-04 22:37:43 浏览: 24
在Spring Boot项目中将HTTP服务升级到HTTPS,需要完成几个步骤:
1. **导入SSL证书**:
- 将你的SSL证书(.crt)文件和私钥(.key)文件复制到项目的`src/main/resources`目录下,通常创建一个名为`certs`的子目录存放。
- 如果有多个证书链(根证书、中间证书),也需要一并提供。
2. **配置application.properties或application.yml**:
- 添加或编辑`server`部分的配置,指定HTTPS端口,如`server.port=8443`(默认8080改为8443),以及SSL相关配置:
```yaml
server:
port: 8443
ssl:
enabled: true
key-store-type: PKCS12
key-store: classpath:certs/your_certificate.p12
key-password: your_password
trust-store: classpath:certs/your_truststore.jks
trust-store-password: your_truststore_password
```
确保填写正确的路径和密码。
3. **启用安全模式**:
- 如果你的证书需要客户端验证(例如浏览器提示“不安全连接”),可以在`server.ssl`配置中设置`requireClientAuth`或`needClientAuth`属性。
4. **添加启动类配置**:
- 如果你的证书是在Spring Boot应用运行时动态加载的,可以考虑使用Spring的`TomcatServletWebServerFactory`,并在启动类上添加SSL支持:
```java
@SpringBootApplication
public class Application implements WebApplicationInitializer {
//...
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
factory.addAdditionalTomcatConnectors(initiateSSLConnector());
SpringApplication.run(Application.class, args, factory);
}
private Connector initiateSSLConnector() {
SslSocketFactory sslSocketFactory = ...; // 初始化SslSocketFactory
return new Connector("org.apache.coyote.http11.Http11NioProtocol")
.setSSLEnabled(true)
.setScheme("https")
.setSecure(true)
.setPort(8443)
.setSocketFactory(sslSocketFactory);
}
}
```
5. **重启应用**:
最后,重新启动Spring Boot应用,它应该会监听HTTPS请求。
阅读全文
相关推荐















