1.下载证书(使用的是阿里云的),springboot项目内置tomcat,所以下载tomcat版本的证书,下载的压缩包里有两个文件
- -pfx后缀的文件 :证书
- -pfx-password.txt :密码
2.将pfx后缀的文件放到项目resources路径下
3.在项目中的application.yml文件配置SSL
server:
port: 443 #使用HTTPS时使用该端口
ssl: #配置HTTPS时打开
key-store: classpath:xxxxx.pfx #证书路径
key-store-password: password #证书密码
key-store-type: PKCS12 #证书类型
4.添加HTTPS配置类
```java
@Configuration
@Slf4j
public class Http2HttpsConfig {
@Bean
public TomcatServletWebServerFactory servletContainer() {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory (){
@Override
protected void postProcessContext(Context context) {
SecurityConstraint securityConstraint = new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
securityConstraint.addCollection(collection);
context.addConstraint(securityConstraint);
}
};
tomcat.addAdditionalTomcatConnectors(httpConnector());
return tomcat;
}
/**
* http 转发到 https
* @return
*/
@Bean
public Connector httpConnector(){
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(80);
connector.setSecure(false);
connector.setRedirectPort(443);
log.info("Http2HttpsConfig - 正式/生产环境通过https访问,启动443端口");
return connector;
}
}
5.项目使用websocket时,需要在页面将ws协议改成wss。
6.本地测试,打开C:\Windows\System32\drivers\etc目录下的host文件,在最后添加 127.0.0.1 www.xxx.com(证书对应域名),然后就可以在浏览器使用www.xxx.com域名进行测试(我主要是想测试HTML5中的Web Notification桌面通知功能)
待解决的问题:
1.application.yml配置中一些SSL配置不正确或多余的时候,springboot项目启动时会提示端口冲突
2.springboot项目启动时,如果找不到证书(证书位置不正确),也会提示端口冲突
3.目前把证书放在resources,yml配置了目录key-store: classpath:xxxxx.pfx classpath:xxxxx.pfx,启动也会提示端口冲突。
只好把证书放在项目根目录下,并将yml配置改成key-store: xxx.pfx
4.以上是前后端不分离的,项目前后端分离的时候,前端和后端都需要各自配置HTTPS,因为HTTPS的页面无法调用非HTTPS的接口或静态文件,不安全,会报错。
本文详细介绍如何在SpringBoot项目中配置HTTPS,包括下载阿里云证书、配置application.yml、添加HTTPS配置类、WebSocket协议调整及本地测试步骤。

3990

被折叠的 条评论
为什么被折叠?



