一、申请SSL证书
SSL证书可在阿里云、腾讯云上购买(可被浏览器信任),也可以通过keytool或openssl生成证书(默认不被信任);
1.通过JDK自动的keytool工具生成证书
新建目录(https),打开CMD进入新建的目录
keytool -genkeypair -alias "tomcat" -keyalg "RSA" -storepass "123456" -
validity 36500 -keystore "f:\https\tomcat.keystore"
2.转换标准格式
keytool -importkeystore -srckeystore f:\https\tomcat.keystore -destkeys
tore f:\https\tomcat.keystore -deststoretype pkcs12
3.查看文件的MD5值
keytool -list -keystore ./tomcat.keystore -V
二、SpringBoot配置HTTPS,并将HTTP访问自动转HTTPS访问
1.证书tomcat.keystore放在application.yml的同级目录;
2.在application.yml文件配置HTTPS
server:
## 访问协议[http/https]
protocol: https
## 访问端口
port: 8442
## 强制转换
mustHttps: true
## SSL安全链接
ssl:
key-store: classpath:tomcat.keystore
key-store-password: 123456
keyStoreType: PKCS12
key-alias=tomcat
3.HTTP访问自转换HTTPS访问
向Spring容器中注入Bean
@Configuration
@EnableConfigurationProperties(ServerConfigProps.class)
public class TomcatContainerConfig {
@Value("${http.port}")
private Integer port;
@Value("${server.port}")
private Integer httpsPort;
@Value("${server.mustHttps}")
private boolean mustHttps;
/**
* 定义Web环境
*
* @return ServletWebServerFactory
*/
@Bean
public ServletWebServerFactory servletWebServerFactory(ServerConfigProps serverProps) {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
@Override
protected void postProcessContext(Context context) {
// 强制使用https
if (mustHttps) {
SecurityConstraint constraint = new SecurityConstraint();
constraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
constraint.addCollection(collection);
context.addConstraint(constraint);
}
}
};
if (mustHttps) {
// 添加http
tomcat.addAdditionalTomcatConnectors(createStandardConnector());
}
// 编码
tomcat.setUriEncoding(Charset.forName(serverProps.getTomcat().getUriEncoding()));
// Tomcat运行模式: Nio/Nio2/APR
tomcat.setProtocol(serverProps.getTomcat().getProtocol());
tomcat.setPort(serverProps.getPort());
return tomcat;
}
/**
* 配置http
*/
private Connector createStandardConnector() {
// 默认协议为org.apache.coyote.http11.Http11NioProtocol
Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
connector.setSecure(false);
connector.setScheme("http");
connector.setPort(port);
// 当http重定向到https时的https端口号
connector.setRedirectPort(httpsPort);
return connector;
}
三、若有单点登录,可在TOMCAT配置HTTPS
1.将证书tomcat.keystore放在/conf目录下;
2.在server.xml文件中,增加Connector
<Connector URIEncoding="UTF-8" SSLEnabled="true" clientAuth="false"
keystoreFile="conf/tomcat.keystore" keystorePass="123456"
maxThreads="150" port="8443"
protocol="org.apache.coyote.http11.Http11NioProtocol"
scheme="https" secure="true" sslProtocol="TLS"/>