Springboot项目配置阿里云ssl证书

服务器资源和接口想要变为 https 的访问方式就需要用到SSL证书,因为是个人使用,我这里使用的是阿里云的一年免费SSL证书。

1,阿里云首页搜索 SSL证书,然后选择 立即购买,在一下页面选择好配置:

2,填写好各种信息之验证通过之后就有了证书,签发之后先下载到本地,因为用的是springboot,我这里是下载的tomcat的

3,文件解压缩之后得到一个后缀为pfx的证书文件 和 一个密码文本文件:

4,将.pfx文件放在 resource目录下,和application配置文件统计:

5,application配置文件中添加一下配置:

http.port =80

server.port=443

server.ssl.key-store=classpath:2952989_www.chienzy.club.pfx

server.ssl.key-store-password=7dTiMef7

server.ssl.keyStoreType=PKCS12

这里可以看到80和443两个端口,80就是HTTP的端口,443就是https的端口

6,利用Tomcat的redirectPort自动重定向到https(80---->443):

当用户用http请求某个资源,而该资源本身又被设置了必须要https方式访问,此时Tomcat会自动重定向到这个redirectPort设置的https端口。

在springboot启动类中加入以下代码:

@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;

}


7,这样就可以在访问http的 80 端口时自动重定向到 https 的  443 端口


 

发布了68 篇原创文章 · 获赞 12 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_38860565/article/details/103872806