服務器資源和接口想要變爲 https 的訪問方式就需要用到SSL證書,因爲是個人使用,我這裏使用的是阿里雲的一年免費SSL證書。
1,阿里雲首頁搜索 SSL證書,然後選擇 立即購買,在一下頁面選擇好配置:
2,填寫好各種信息之驗證通過之後就有了證書,簽發之後先下載到本地,因爲用的是springboot,我這裏是下載的tomcat的
3,文件解壓縮之後得到一個後綴爲pfx的證書文件 和 一個密碼文本文件:
4,將.pfx文件放在 resource目錄下,和application配置文件統計:
5,application配置文件中添加一下配置:
http.port =80
server.port=443
server.ssl.key-store=classpath:2952989_www.chienzy.club.pfx
server.ssl.key-store-password=7dTiMef7
server.ssl.keyStoreType=PKCS12
這裏可以看到80和443兩個端口,80就是HTTP的端口,443就是https的端口
6,利用Tomcat的redirectPort自動重定向到https(80---->443):
當用戶用http請求某個資源,而該資源本身又被設置了必須要https方式訪問,此時Tomcat會自動重定向到這個redirectPort設置的https端口。
在springboot啓動類中加入以下代碼:
@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(80);
connector.setSecure(false);
connector.setRedirectPort(443);
return connector;
}
7,這樣就可以在訪問http的 80 端口時自動重定向到 https 的 443 端口