Spring Boot配置ssl證書啟用HTTPS協議

  • 2019 年 10 月 8 日
  • 筆記

一 、點睛

SSL是為網路通訊提供安全及數據完整性的一種安全協議,SSL在網路傳輸層對網路連接進行加密。SSL協議位於TCP/IP協議和各種應用層協議之間,為數據通訊提供安全支援。

SSL協議分為兩層:SSL記錄協議,它建立在可靠的傳輸協議(如TCP)之上,為高層協議提供數據封裝、壓縮、加密等基本功能的支援。SSL握手協議,它建立在SSL記錄協議之上。用於在實際數據傳輸開始前,通訊雙方進行身份認證、協商加密演算法、交換加密密鑰等。

基於B/S的Web應用中,是通過HTTPS來實現SSL的。HTTPS是以安全為目標的HTTP通訊,簡單講是HTTP的安全版,即在HTTP下加入SSL層,HTTPS的安全基礎是SSL。 !

二、用JDK中keytool生成自帶簽名證書

使用SSL首先需要一個證書,這個證書既可以是自簽名的,也可以是從SSL證書授權中心獲得的。本案例演示自簽名證書的生成。

JDK或JRE中的keytool工具是一個證書管理工具,可以用來生成自簽名證書。

在命令行輸入以下內容

此時生成一個.keystore文件,這就是我們要用的證書文件

三、將.keystore證書文件(複製到項目的application.properties同級目錄)

四、修改Spring Boot的application.properties

五、修改啟動類,讓http重定向到https

XXXApplication.java

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;

@SpringBootApplication

public class WebchatApplication {

public static void main(String[] args) { SpringApplication.run(WebchatApplication.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(8044); return connector; } }

啟動成功後,打開Chrome瀏覽器,輸入SpringBoot的URL映射,可以看到彈出了證書不安全的提示,單擊【高級】–>【繼續前往】即可正常打開網址鏈接了。

注意:由於JDK生成的自簽名證書沒有經過CA機構認證,所以會提示不安全。