Spring Boot自动将HTTP重定向到https [英] spring boot automatic redirect http to https

查看:78
本文介绍了Spring Boot自动将HTTP重定向到https的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

美好的一天,我在SpringBoot 2上构建了带有微服务和网关(zuul)的应用程序.它们全部使用SSL.我需要从以下位置自动重定向:http:\\ localhost(当前不显示任何内容)到https:\\ localhost(显示一些文本),因此用户无需理会.

Good day, I have the application with microservices and gateway (zuul) built on SpringBoot 2. It is all uses SSL. I need the automatic redirect from: http:\\localhost (currently shows nothing) to https:\\localhost (shows some text), so the user doesn't need to bother.

再次:http:\\ localhost必须显示与https:\\ localhost相同的文本(我需要重定向)

Once again: http:\\localhost has to show the same text as https:\\localhost (I need a redirect)

我已经尝试过,什么也不做.

I've tried, does nothing.

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requiresChannel().anyRequest().requiresSecure();
    }
}

尝试了另一种方法,但是SpringBoot无法识别TomcatEmbeddedServletContainerFactory

Tried another approach, but SpringBoot failed to recognize TomcatEmbeddedServletContainerFactory

@Bean
public EmbeddedServletContainerFactory servletContainer() {
    TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {

        @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(createHttpConnector());
    return tomcat;
}

private Connector createHttpConnector() {
    Connector connector
            = new Connector("org.apache.coyote.http11.Http11NioProtocol");
    connector.setScheme("http");
    connector.setSecure(false);
    connector.setPort(8080);
    connector.setRedirectPort(8443);
    return connector;
}

此功能也不起作用(似乎没有任何改变)

this one doesn't work either (doesn't seems to change anything)

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private Environment environment;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        // other security configuration missing

        http.portMapper()
                .http(80) // http port defined in yml config file
                .mapsTo(443); // https port defined in yml config file

        // we only need https on /auth
        http.requiresChannel()
                .antMatchers("/auth/**").requiresSecure()
                .anyRequest().requiresInsecure();
    }
}

并且此功能也不起作用,错误是无法实例化[org.springframework.web.servlet.HandlerMapping]:工厂方法'resourceHandlerMapping'抛出异常;嵌套异常为java.lang.IllegalStateException:未设置ServletContext

and this one ain't working too, the error is Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'resourceHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: No ServletContext set

@Bean
public TomcatServletWebServerFactory httpsRedirectConfig() {
    return 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);
        }
    };
}

,甚至是带有 java.lang.IllegalStateException的代码:没有设置ServletContext 错误

  @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(80);
        connector.setSecure(false);
        connector.setRedirectPort(443);
        return connector;
    }

有什么建议吗?

推荐答案

知道了.感谢 EstebanGarciaAlonso 和他的回答

调试后,问题在于该mvc配置类EnableWebMvcConfiguration加载太早,尚未加载servlet."

"After debugging, the problem is that mvc configuration class EnableWebMvcConfiguration load too early, servlet not loaded yet."

我花了几个小时.我设法找到一个原因发生.我的配置被分成几个文件,我正在创建一个Security Config中的MVC相关Bean(先前创建)强制在其时间之前使用MVC配置.

I spent a few hours on this. I managed to find a reason why this was happening. My config was split into several files and I was creating a MVC related bean in the Security Config (which was created earlier) forcing to use the MVC config before its time.

解决方案是从安全配置中移动@Bean实例到MVC配置.我希望它对其他人有帮助!

The solution was to move the @Bean instance from the security config to the MVC config. I hope it helps other people!

我在主要方法之前将以下代码移至Application.java,并且一切都像奇迹一样

I moved following code to Application.java just before main method and all worked like miracle

   @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(80);
        connector.setSecure(false);
        connector.setRedirectPort(443);
        return connector;
    }

这篇关于Spring Boot自动将HTTP重定向到https的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆