Spring boot 在Spring Boot中通过代理将HTTP定向到HTTPS

Spring boot 在Spring Boot中通过代理将HTTP定向到HTTPS,spring-boot,spring-security,Spring Boot,Spring Security,我有一个用SpringBoot(2.0.5)编写的服务器。它位于提供SSL的代理服务器后面。代理同时接受HTTP(80)和HTTPS(443),并将两者转发到我的服务器,该服务器只在端口2222上接受HTTP。代理设置以下请求头 x-for x-proto x端口 我在WebSecurityConfig类中测试了以下代码,但它不起作用 @Override protected void configure(HttpSecurity httpSecurity) throws Exception

我有一个用SpringBoot(2.0.5)编写的服务器。它位于提供SSL的代理服务器后面。代理同时接受HTTP(80)和HTTPS(443),并将两者转发到我的服务器,该服务器只在端口2222上接受HTTP。代理设置以下请求头

  • x-for
  • x-proto
  • x端口
我在
WebSecurityConfig
类中测试了以下代码,但它不起作用

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
     httpSecurity.requiresChannel().anyRequest().requiresSecure()
     .and().
     ...  
}
我还编写了以下代码将HTTP重定向到HTTPS。但它也重定向HTTPS流量。但我只需要重定向HTTP

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.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class HttpsConfiguration {

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

我正在寻找一种方法来检查请求头,如果是HTTP,我想将其重定向到HTTPS。

您提供的Spring安全配置应该可以工作。我猜问题在于你没有正确回答。要启用支持,应指定:

server.use-forward-headers=true
注意:如果应用程序在Cloud Foundry或Heroku中运行,则server.use-forward-headers属性默认为true。在所有其他情况下,它默认为false

我会特别关注这个问题。这就是造成大多数人问题的原因。Tomcat依赖一个附加设置来确定内部代理IP地址是否与默认正则表达式匹配。如果代理的IP与正则表达式不匹配,它会自动忽略转发的头

如果您在这方面遇到困难,请尝试指定以下内容:

server.tomcat.internal-proxies=.*

注意:其他应用程序服务器不关心代理IP地址,如果客户端可以欺骗X转发的头,那么它也可以欺骗IP地址,因此向每个IP地址打开它不会对您的应用程序产生影响。

这些属性仅对嵌入的tomcat服务器有效,对吗?