運維給了兩個證書文件,一個是.key 和.crt
需要在我的項目中配置ssl,
我所使用的是p12的類型,參考的網址:在Spring Boot中配置ssl證書實現https - 簡書 (jianshu.com)
首先我們需要生成.p12的文件,文件需要一個插件OpenSSL
OpenSSL官網,
官方下載地址: https://www.openssl.org/source/
OpenSSL官網沒有提供windows版本的安裝包,可以選擇其他開源平台提供的工具。例如 http://slproweb.com/products/Win32OpenSSL.html
參考網址: Windows安裝使用Openssl_microcosm1994的博客-CSDN博客_openssl安裝
安裝完成后,進入openSSL 的bin目錄下 cmd,輸入
openssl pkcs12 -export -clcerts -in yourDomain.crt -inkey myPrivateKey.key -out server.p12
-
yourDomain.crt 替換為你的 crt 文件
-
myPrivateKey.key 替換為你的 key 文件
-
在此過程中需要讓你輸入密碼,記住這個密碼,后面會用到
-
執行此命令,生成了我們需要的 p12 文件,將其復制到 spring boot 項目中的 src/main/resources/ 目錄下,和 application.properties 平級
springboot項目配置
1 server 2 ssl: 3 key-store: server.p12 4 key-store-password: jsc111 5 key-store-type: PKCS12 6 enabled: true
然后再啟動類中配置如下代碼,
1 @Bean 2 public ServletWebServerFactory servletContainer() { 3 TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory(){ 4 protected void postProcessContext(Context context) { 5 SecurityConstraint securityConstraint = new SecurityConstraint(); 6 securityConstraint.setUserConstraint("CONFIDENTIAL"); 7 SecurityCollection collection = new SecurityCollection(); 8 collection.addPattern("/*"); 9 securityConstraint.addCollection(collection); 10 context.addConstraint(securityConstraint); 11 } 12 }; 13 tomcat.addAdditionalTomcatConnectors(httpConnector()); 14 return tomcat; 15 } 16 17 @Bean 18 public Connector httpConnector() { 19 Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); 20 connector.setScheme("http"); 21 connector.setPort(80); //Connector監聽的http的端口號 22 connector.setSecure(false); 23 connector.setRedirectPort(8808); //監聽到http的端口號后轉向到的https的端口號 24 return connector; 25 }
然后訪問你的項目地址成功訪問即可完成
我在啟動的時候遇到了一個報錯
keytool error: java.io.IOException: parseAlgParameters failed: ObjectIdentifier() -- data isn't an object ID (tag = 48)
此報錯代表你的java版本過低,需要升級到 8u301 或者 11.0.1版本
我所記錄的僅為我找的的方法,只是在本地使用,服務器需要再進行配置,僅供參考