SpringBoot配置https並實現http訪問自動跳轉https(自定義證書)

一、準備

elasticsearch-7.3.2(下載解壓即可用)

SpringBoot2.1.2

二、生成證書

使用elasticsearch-certutil生成springboot.p12證書

elasticsearch-certutil官方文檔

https://www.elastic.co/guide/en/elasticsearch/reference/7.6/certutil.html

1創建ca認真中心

elasticsearch-certutil ca

會提示輸入文件名和密碼

文件在第2步中使用

2使用ca創建證書

D:\backup\elk\elastic_stack_7.3.2\elasticsearch-7.3.2\bin>elasticsearch-certutil cert --ca-cert C:\Users\admin\Desktop\ca\ca.crt --ca-key C:\Users\admin\Desktop\ca\ca.key --dns logstash --ip 127.0.0.1 --name springboot

記住剛纔輸入的密碼

得到文件

三、SpringBoot配置

將springboot.p12拷貝到resources目錄

application.properties

#端口號
#https端口
server.port=8080
#http端口
server.httpPort=8081
#日誌配置
logging.config=classpath:logback-spring.xml
#服務器名稱
serverName=test_server
#配置ssl
server.ssl.enabled=true
server.ssl.key-store=classpath:springboot.p12
server.ssl.key-store-password=123456
server.ssl.key-store-type=PKCS12
# 證書別名
server.ssl.key-alias=springboot

http重定向到https,配置類

package com.asyf.demo.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.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SSLConfig {

    @Value("${server.httpPort}")
    int httpPort;
    @Value("${server.port}")
    int httpsPort;

    @Bean(name = "connector")
    public Connector connector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        connector.setPort(httpPort);
        connector.setSecure(false);
        connector.setRedirectPort(httpsPort);
        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;
    }
    
}

 四、啓動測試

1重定向測試:訪問http://127.0.0.1:8081/test?num=1hi跳轉到https://127.0.0.1:8080/test?num=1

2https測試:直接訪問https://127.0.0.1:8080/test?num=1

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章