SpringBoot2.x配置Https

准备工作

需要自签,或者权威机构颁发的证书一张

springboot配置Https访问

#ssl
#https访问的端口
server.port=8085
#证书,可以存放在resoucrs目录下
server.ssl.key-store=classpath:tomcat_ssl/www.huimaida.com.jks
#证书密码
server.ssl.key-password=223311
#证书加密方式
server.ssl.key-store-type=JKS

以上,便完成可https的访问配置,例如:https://127.0.0.1:8085/

配置http跳转https

我们可以配置http访问某个端口,自动跳转至https端口。例如,配置80端口,当用户通过  http://127.0.0.1:80/  访问时,会自动跳转至配置另外的一个端口。

配置如下:

    @Bean
    //配置http某个端口自动跳转https
    public TomcatServletWebServerFactory 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(initiateHttpConnector());
        return tomcat;
    }

    private Connector initiateHttpConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        //监听的http端口
        connector.setPort(8005);
        connector.setSecure(false);
        //跳转的https端口
        connector.setRedirectPort(8085);
        return connector;
    }

 

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