给自己的网站加上SSL安全认证
首先下载证书
文件解压缩之后得到一个后缀为pfx的证书文件 和 一个密码文本文件
将后缀为pfx的证书文件放在resources目录下
在application.yml文件中配置
server.port=443是https的端口
#https配置
server.port=443
server.ssl.key-store=classpath:xxxx.pfx
server.ssl.key-store-password=xxxx
server.ssl.key-store-type=PKCS12
当用户用http请求某个资源,而该资源本身又被设置了必须要https方式访问,此时Tomcat会自动重定向到这个redirectPort设置的https端口。
@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;
}
注意:
这里必须在服务器运行, 本地不能运行。
然后我跑了两个相同的项目,都是转到相同的https上
http://qykhhr.top/upload/images/163877678430001568126609975.jpg (运行在80端口上)
http://qykhhr.top:9000/upload/images/163877678430001568126609975.jpg (运行在9000端口上)
两个都转到了https://qykhhr.top/upload/images/163877678430001568126609975.jpg
到此完成~