在阿里云上购买过域名并将域名备案之后,购买一个SSL证书,我都已经购买过了,并且将域名与SSL绑定好了
image.png
在Spring Boot项目中配置SSL证书相关
1.证书下载
证书有多个版本,选择tomcat下载
2.将证书中的pfx复制到resources下面,与application.properties同一级
3.在application.properties中添加https证书相关配置
#https证书
#https加密端口号
server.port=9090
#SSL证书路径,一定要加上classpath
server.ssl.key-store=classpath:证书的名称(例如:2034442_sys.mamamama.top.pfx)
#SSL证书密码
server.ssl.key-store-password=证书密码例如:Xcu4l23o
#SSL证书类型
server.ssl.keyStoreType=PKCS12
4.修改启动类,让http请求定位到https
/**
* http重定向到https
* @return
*/
@Bean
public TomcatServletWebServerFactory servletWebServerFactory() {
TomcatServletWebServerFactory tomcatServletWebServerFactory = new TomcatServletWebServerFactory() {
@Override
protected void postProcessContext(Context context) {
SecurityConstraint constraint = new SecurityConstraint();
constraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
constraint.addCollection(collection);
context.addConstraint(constraint);
}
};
tomcatServletWebServerFactory.addAdditionalTomcatConnectors(httpConnector());
return tomcatServletWebServerFactory;
}
@Bean
public Connector httpConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
//Connector监听的http的端口号
connector.setPort(9092);
connector.setSecure(false);
//监听到http的端口号后转向到的https的端口号
connector.setRedirectPort(9090);
return connector;
}
这样当我们用http访问9092端口时,会自动转向https的9090端口
网友评论