一.SSL证书
在阿里云申请免费SSL证书,并下载tomcat版本,解压后会得到两个文件,一个是ca证书(pfx后缀的文件),另一个是ca密码
二.阿里云上配置安全组规则
image.pngimage.png
三.代码部分
1.application.properties
server.port = 443
server.ssl.key-store=C:/v1.0/123.com.pfx
server.ssl.key-store-password=你的密码
server.port = 443是https的默认端口
其中server.ssl.key-store的值是ca证书路径
server.ssl.key-store-password是证书密码
2.在springboot启动类里面添加代码
public static void main(String[] args) {
SpringApplication.run(QbtApplication.class, args);
}
@Bean
public TomcatServletWebServerFactory servletContainer() {
TomcatServletWebServerFactory tomcat = 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);
}
};
tomcat.addAdditionalTomcatConnectors(httpConnector());
return tomcat;
}
@Bean
public Connector httpConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
//Connector监听的http的端口号
connector.setPort(80);
connector.setSecure(false);
//监听到http的端口号后转向到的https的端口号
connector.setRedirectPort(443);
return connector;
}
四.测试
发布到阿里云服务器,测试如下
image.png
成功!!!
网友评论