一罗晕、申請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.轉(zhuǎn)換標準格式
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訪問自動轉(zhuǎn)HTTPS訪問
1.證書tomcat.keystore放在application.yml的同級目錄币他;
2.在application.yml文件配置HTTPS
server:
## 訪問協(xié)議[http/https]
protocol: https
## 訪問端口
port: 8442
## 強制轉(zhuǎn)換
mustHttps: true
## SSL安全鏈接
ssl:
key-store: classpath:tomcat.keystore
key-store-password: 123456
keyStoreType: PKCS12
key-alias=tomcat
3.HTTP訪問自轉(zhuǎn)換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環(huán)境
*
* @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() {
// 默認協(xié)議為org.apache.coyote.http11.Http11NioProtocol
Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
connector.setSecure(false);
connector.setScheme("http");
connector.setPort(port);
// 當(dāng)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"/>