1. 申請騰訊雲免費ssl證書
1.1 登陸騰訊雲在我的證書列表頁面點擊申請免費證書
2.2 提交資料,必填證書綁定域名以及申請郵箱,綁定域名填寫springboot項目部署的服務器域名
2.3 選擇驗證方式,默認即可
2.4 驗證域名,一般2、3分鍾就驗證完畢了
2.5 驗證完畢后在證書列表頁面下載證書文件,選擇tomcat目錄下的jks文件即可
證書列表
證書壓縮包文件
2. springboot配置ssl證書
1.1 將jks文件導入springboot項目resoures目錄下
2.2 在application.yml
文件中配置如下代碼
server:
port: 443
ssl: # ssl相關配置
enabled: true
key-store: classpath:mall.wayn.ltd.jks
key-store-password: idFXdK.Rnm3CgZp
key-store-type: JKS
http-port: 8080 # http重定向https配置
2.3 添加HttpsConfiguration
文件,將 HTTP 請求重定向到HTTPS
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.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class HttpsConfiguration {
@Value("${http-port}")
private int port;
@Value("${server.port}")
private int sslPort;
@Bean
public ServletWebServerFactory servletContainer() {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
@Override
protected void postProcessContext(Context context) {
SecurityConstraint securityConstraint = new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
securityConstraint.addCollection(collection);
context.addConstraint(securityConstraint);
}
};
tomcat.addAdditionalTomcatConnectors(redirectConnector());
return tomcat;
}
private Connector redirectConnector() {
Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
connector.setScheme("http");
connector.setPort(port);
connector.setSecure(false);
connector.setRedirectPort(sslPort);
return connector;
}
}
- 訪問瀏覽器http://localhost8080,會自動重定向到https://localhost