无法为静态资源禁用HSTS标头

时间:2019-09-10 14:06:39

标签: java spring spring-boot https hsts

简介:

我们有一个SpringBoot(v2.1.3)应用程序作为后端,而Angular 8作为前端。 Angular应用程序作为静态资源打包到spring boot .jar文件中。 嵌入式tomcat用作服务器。 正在使用两个端口,一个用于http模式,另一个用于https模式。 应用程序应在https上运行,但保持http端口不中断现有应用程序链接。 从Http到https重定向已配置。 HSTS已禁用。

问题:

用户可以在第一次尝试时访问http端口,并以301状态成功重定向到https端口。

在下一次尝试访问http端口(显式指定该事件后)时,浏览器默认使用https,http连接器无法解释该请求并引发错误(o.apache.coyote.http11.Http11Processor:错误解析HTTP请求标头-java.lang.IllegalArgumentException:在方法名称中发现无效字符。HTTP方法名称必须是令牌。)

我知道此行为是由HSTS标头引起的,该标头规定了整个域的严格HTTPS通信规则。因此,只需要一个包含HSTS标头的响应,对于试图访问应用程序http部分的用户来说,整个域就被破坏了。

只有静态服务的文件具有HSTS标头,其他响应(例如REST)不包含此标头。

我尝试创建安全过滤器以覆盖标头值,并且如果在SwitchUserFilter之后(它是安全过滤器链中最后一个预定义的过滤器)之后,则排队。此时,HttpServletResponse不包含HSTS标头。

我试图创建自己的ResourceHttpRequestHandler并提供它来代替默认值。我无法解决此问题,因为在此类的setHeaders()方法中,HSTS标头尚不存在。

在TomcatServletWebServerFactory的方法postProcessContext中,我为资源URL模式设置了NONE用户约束。没有帮助 -资源只是使用http端口加载的。

重定向的设置如下: https://stackoverflow.com/a/52803328/7678068

    @Bean
    public ConfigurableServletWebServerFactory httpRedirectToHttps(@Value("${https}") String serverPort,
                                                                   @Value("${http}") String serverHttpPort) {

        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint constraint = new SecurityConstraint();
                constraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection securityCollection = new SecurityCollection();
                securityCollection.addPattern("/*");
                constraint.addCollection(securityCollection);
                context.addConstraint(constraint);
                super.postProcessContext(context);
            }
        };

        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        connector.setSecure(false);
        connector.setPort(Integer.parseInt(serverHttpPort));
        connector.setRedirectPort(Integer.parseInt(serverPort));
        tomcat.addAdditionalTomcatConnectors(connector);

        return tomcat;
    }

HSTS的配置如下: https://docs.spring.io/spring-security/site/docs/4.0.x/reference/html/headers.html


        @Override
        protected void configure(HttpSecurity config) throws Exception {

            config.headers().httpStrictTransportSecurity().disable();

        }

因此,HSTS的部分禁用有效。有人知道如何解决这个问题吗?

0 个答案:

没有答案