SpringBoot 集成 https

253 阅读1分钟

生成证书

使用 jdk 自带的 keytool 命令生成证书复制到项目的 resources 目录下(生成的证书一般在用户目录下 C:\Users\Administrator\server.keystore)

keytool -genkey -alias tomcat -keyalg RSA -keystore ./server.keystore

image-20221009195017073.png 注意:自己使用命令生成的证书会有危险提示,在网站上花钱申请则不会存在安全提示。

添加配置

  • 在配置文件中配置生成的证书
 server:
   ssl:
     # 证书路径
     key-store: classpath:server.keystore
     key-alias: tomcat
     enabled: true
     key-store-type: JKS
     #与申请时输入一致
     key-store-password: 0401meng
     # 浏览器默认端口和 80 类似
   port: 456
  • 配置 Tomcat
 package com.project.https.config;
 ​
 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.web.embedded.tomcat.TomcatServletWebServerFactory;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
 ​
 /**
  * @author
  * @time 2022/10/9 18:39
  */
 @Configuration
 public class HttpsConfig {
 ​
     /**
      * 配置 http(80) -> 强制跳转到 https(443)
      */
     @Bean
     public Connector connector() {
         Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
         connector.setScheme("http");
         connector.setPort(8080);
         connector.setSecure(false);
         connector.setRedirectPort(456);
         return connector;
     }
 ​
     @Bean
     public TomcatServletWebServerFactory tomcatServletWebServerFactory(Connector connector) {
         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(connector);
         return tomcat;
     }
 }

测试

在浏览器地址输入:

http://localhost:8080/index.html

将会重定向到:

https://localhost:456/index.html