1. 程式人生 > >SpringBoot配置SSL證書支持

SpringBoot配置SSL證書支持

font .class lec sts fill connector alias sets redirect

純copy 非原創,原文鏈接:https://blog.csdn.net/sinat_40399893/article/details/79860942

Spring Boot配置ssl證書

一、申請有權威的SSL證書

在各大雲服務商都可以申請到SSL官方證書。
我這裏是在阿裏雲上申請的,申請後下載,解壓。如圖:
技術分享圖片

二、用JDK中keytool是一個證書管理工具,壓縮成tomcat所支持的.jks

1、打開你安裝的jdk目錄下

技術分享圖片

2、打開dos命令框(命令提示符)

2.1、進入JDK所在的盤符,我的是D盤
2.2、進入JDK下的bin目錄
2.3、輸入這條命令(輸入之前先修改:D:\https\214215109110451\214215109110451.pfx 部分是你下載的證書pfx所在路徑,520oo.jks是自己命名的jks文件)

keytool -importkeystore -srckeystore D:\https\214215109110451\214215109110451.pfx -destkeystore 520oo.jks -srcstoretype PKCS12 -deststoretype JKS
  • 1

2.4、輸入密碼,三次輸入的密碼都要和解壓的證書裏密碼一致,不一致有可能出錯。
2.5、記下別名:alias
技術分享圖片
2.6、在bin目錄下找到 jks文件(復制到項目的application.properties同級目錄)
技術分享圖片
技術分享圖片

三、修改Spring Boot的application.properties

#https加密端口號 443
server.port=443
#SSL證書路徑 一定要加上classpath:
server.ssl.key-store=classpath:520oo.jks
#SSL證書密碼
server.ssl.key-store-password=214215109110451
#證書類型
server.ssl.key-store-type=JKS
#證書別名
server.ssl.key-alias=alias

四、修改啟動類,讓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(443);
      return connector;
   }
}

然後大功告成

SpringBoot配置SSL證書支持