springboot配置https访问

springboot配置https访问

接口如图所示

将jks文件拖入resource文件下。

编辑 yml文件

server:
  port: 18040  
  custom:
    port: 8040
  ssl:
    key-store: classpath:xxxxxxx.jks
    key-password: 密码
    key-store-password: 密码
    key-store-type: JKS

新增HttpsConfig文件

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 HttpsConfig {

    @Value("${server.custom.port}")
    private Integer httpport;

    @Value("${server.port}")
    private Integer httpsPort;

    //如果要同时拥有http并重定向至https端口上,可用下面的代码实现

    @Bean
    public TomcatServletWebServerFactory tomcatServletWebServerFactory() {
        TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection securityCollection = new SecurityCollection();
                securityCollection.addPattern("/*");
                securityConstraint.addCollection(securityCollection);
                context.addConstraint(securityConstraint);
            }
        };
        factory.addAdditionalTomcatConnectors(httpConnector());
        return factory;
    }

    @Bean
    public Connector httpConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        //Connector监听的http的端口号
        connector.setPort(httpport);
        connector.setSecure(false);
        //监听到http的端口号后转向到的https的端口号
        connector.setRedirectPort(httpsPort);
        return connector;
    }
}

上一篇:Oracle 11g数据库详细安装步骤图解


下一篇:mysql下载安装、输入密码check后出错、Connector/Net卸载不干净、使用工具连接等问题解决