学习内容:
一、申请SSL证书
在来此加密申请免费的SSL证书。
文件说明:
- fullchain.crt: 证书和证书链
- certificate.crt: 证书
- chain.crt: 证书链
- chain_old.crt: 低版本系统证书链
- private.pem: 密钥(请妥善保存)
- public.pem: 公钥
- certificate.pfx: pfx格式证书(使用pfx导入密码)
二、用JDK中keytool是一个证书管理工具,压缩成tomcat所支持的.jks
- D:\BUSINESS\2021\07\2lrjg7.20220413\certificate.pfx 是证书pfx所在路径。
- aksyun.jks 是自己命名的jks文件
keytool -importkeystore -srckeystore D:\BUSINESS\2021\07\2lrjg7.20220413\certificate.pfx -destkeystore aksyun.jks -srcstoretype PKCS12 -deststoretype JKS
- JKS 密钥库使用专用格式。建议使用 “keytool -importkeystore -srckeystore aksyun.jks -destkeystore aksyun.jks -deststoretype pkcs12” 迁移到行业标准格式 PKCS12。(按照提示复制到命令行执行)
- 在bin目录下找到 jks文件(复制到项目的application.yml同级目录)
三、修改Spring Boot的application.yml
四、修改启动类,让http重定向到https
package com.jiaran.conon.wechat;
import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
/**
* @author 过儿
* @date 2022/1/18 0018 14:54
* @deprecated
*/
@SpringBootApplication
public class WeChatApplication {
public static void main(String[] args) {
SpringApplication.run(WeChatApplication.class, args);
}
/**
* http重定向到https
* @return
*/
@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(8080);
connector.setSecure(false);
//监听到http的端口号后转向到的https的端口号
connector.setRedirectPort(443);
return connector;
}
}