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

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