Springboot配置https,使用騰訊雲免費證書

1. 申請騰訊雲免費ssl證書

1.1 登錄騰訊雲在個人證書列表頁面點擊申請免費證書web

企業微信截圖_20210419145434.png
2.2 提交資料,必填證書綁定域名以及申請郵箱,綁定域名填寫springboot項目部署的服務器域名spring

企業微信截圖_20210419145537.png

2.3 選擇驗證方式,默認便可apache

企業微信截圖_20210419145805.png
2.4 驗證域名,通常二、3分鐘就驗證完畢了瀏覽器

企業微信截圖_20210419145827.png

2.5 驗證完畢後在證書列表頁面下載證書文件,選擇tomcat目錄下的jks文件便可tomcat

證書列表
企業微信截圖_20210419151236.png
證書壓縮包文件
企業微信截圖_20210419150107.pngspringboot

2. springboot配置ssl證書

1.1 將jks文件導入springboot項目resoures目錄下服務器

企業微信截圖_20210419150306.png

2.2 在application.yml文件中配置以下代碼微信

server:
  port: 443
  ssl: # ssl相關配置
    enabled: true
    key-store: classpath:mall.wayn.ltd.jks
    key-store-password: idFXdK.Rnm3CgZp
    key-store-type: JKS

http-port: 8080 # http重定向https配置

2.3 添加HttpsConfiguration文件,將 HTTP 請求重定向到HTTPSapp

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.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class HttpsConfiguration {

    @Value("${http-port}")
    private int port;

    @Value("${server.port}")
    private int sslPort;

    @Bean
    public ServletWebServerFactory servletContainer() {
        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(redirectConnector());
        return tomcat;
    }

    private Connector redirectConnector() {
        Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
        connector.setScheme("http");
        connector.setPort(port);
        connector.setSecure(false);
        connector.setRedirectPort(sslPort);
        return connector;
    }

}
  1. 訪問瀏覽器http://localhost8080,會自動重定向到https://localhost
相關文章
相關標籤/搜索