Spring Boot配置腾讯云SSL证书

一、申请有权威的SSL证书

我是在腾讯云申请的

二、jks文件复制到项目的application.properties同级目录

Spring Boot配置腾讯云SSL证书_第1张图片

三、修改Spring Boot的application.properties

#https加密端口号 443
server.port=443
#SSL证书路径 一定要加上classpath:
server.ssl.key-store=classpath:www.dorabox.club.jks
#SSL证书密码
server.ssl.key-store-password=214215109110451(密码在第一步的keystorePass.txt中)
#证书类型
server.ssl.key-store-type=JKS

四、修改启动类,让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;
   }
}

然后大功告成,有了绿色的小锁,下面是效果:
è¿éåå¾çæè¿°

你可能感兴趣的:(linux,java)