-
我使用的是阿里云免费ssl证书,申请一下通过审核就好
-
签发之后先下载到本地,我这里是下载的tomcat的
-
解压缩之后得到这两个东西:
-
将.pfx文件放到springboot项目的resources目录下:
在applicatio.yml中添加配置:
http:
port: 80
server:
port: 443
ssl:
key-store: classpath:1655744_nichang.site.pfx
key-store-password: xxxxxx(pfx-password.txt中的内容)
keyStoreType: PKCS12
- 设置自动重定向http到https(80端口->443端口):
在启动类中加入以下代码:(注意网上有些代码中的EmbeddedServletContainerFactory找不到是因为springboot2.X之后改了写法)
@Bean
public ServletWebServerFactory 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(redirectConnector());
return tomcat;
}
private Connector redirectConnector() {
Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
connector.setScheme("http");
connector.setPort(80);
connector.setSecure(false);
connector.setRedirectPort(443);
return connector;
}
- 这样就可以在访问80端口时自动重定向到https