负载均衡器后面带有 Spring Security 的 Spring Boot:将 HTTP 重定向到 HTTPS

del*_*svb 5 java tomcat spring-security amazon-web-services spring-boot

我正在使用 Elastic Beanstalk 部署 Spring Boot Web 服务器,在应用程序负载均衡器 (Elastic Load Balancer) 后面运行。业务规则是只能通过 HTTPS 联系此 Web 服务器。因此任何 HTTP 请求都必须首先转发到 HTTPS。

根据Amazon 的这篇文章,我应该简单地检查由负载均衡器设置的x-forwarded-for和标头。x-forwarded-proto这些标头包含有关客户端向负载均衡器发出的原始请求的信息。

因此,我开始寻找 Spring Boot 的内置方法(顺便说一句,我正在使用内置的 Tomcat 服务器)来检查这两个标头并进行重定向,而不必自己编写太多代码。Spring Boot(我们使用的是 1.4 版)文档声明要使用以下应用程序属性:

security.require_ssl=true
server.tomcat.remote_ip_header=x-forwarded-for
server.tomcat.protocol_header=x-forwarded-proto
Run Code Online (Sandbox Code Playgroud)

使用 Postman 进行测试会得到 HTTP 200,我应该在其中获得 301/302 重定向。我怀疑这是由于我使用 Spring Security 造成的。为了使其与 Spring Security 一起工作,我可以将其添加到我的WebSecurityConfigurerAdapter

 http.requiresChannel().anyRequest().requiresSecure();
Run Code Online (Sandbox Code Playgroud)

但现在我的标头被忽略,所有请求都转发到 HTTPS,即使原始请求已经是 HTTPS 了。所以现在没有任何作用。

罗德里戈·克萨达(Rodrigo Quesada)在这里的答案似乎是我所需要的,但由于某种原因,它仍然不尊重我的标题。这个请求仍然给我一个重定向而不是 200:

GET / HTTP/1.1
Host: localhost:8080
X-Forwarded-Proto: https
X-Forwarded-For: 192.168.0.30
Run Code Online (Sandbox Code Playgroud)

这里和其他网站上还有许多其他解决方案,使用另一个中间 Web 服务器,或者在 AWS 上配置 NGINX 或 Apache 来执行重定向。但我已经在使用 Tomcat,为什么还要配置另一个Web 服务器。

那么我如何才能以 Spring 方式实际配置 Spring Boot/Tomcat/Spring Security 来执行此重定向呢?有没有办法扩展函数的行为,requiresSecure()以便它考虑我的请求标头?或者更好的是,是否有任何 Spring Security 替代我尝试过的应用程序属性?

del*_*svb 1

我现在用一些自定义逻辑修复了它。在将A传递给任何 REST 控制器之前,HandlerInterceptor可以对其进行注册以进行检查。HttpServletRequest它看起来像这样:

private HandlerInterceptor protocolInterceptor() {
    return new HandlerInterceptorAdapter() {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
            String forwardedProtocol = request.getHeader("x-forwarded-proto");

            // x-forwarded-proto header is required, send 400 if it's missing
            if (forwardedProtocol == null) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "x-forwarded-proto header required from the load balancer");
                return false;
            }

            // Client request protocol must be https, send 301 if it's http
            if (!forwardedProtocol.equals("https")) {
                String host = request.getHeader("host");

                // Send error 400 if 'host' is empty
                if (host == null) {
                    response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Host header missing");
                    return false;
                }

                response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
                response.setHeader("Location", "https://" + host + request.getServletPath());
                return false;
            }

            // All is well in all other cases, continue
            return true;
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

x-forwarded-proto首先检查标头是否存在。如果没有,我会发送客户端错误响应。然后我检查标头值,该值必须是 https。HTTP 1.1 始终有一个host标头,但以防万一我也检查该标头是否为空值。最后我发送了 301 永久重定向。请注意,我将拦截器放在一个方法中,但您也可以用它制作一个 bean。

接下来我们需要注册拦截器。如果您还没有,请创建一个扩展WebMvcConfigurerAdapter并重写该addInterceptors方法的配置类:

@Override
public void addInterceptors(InterceptorRegistry registry) {
    logger.info("Registering custom interceptors");
    logger.debug("Registering protocol interceptor to redirect http to https");
    registry.addInterceptor(protocolInterceptor());
    logger.info("Registered custom interceptors");
}
Run Code Online (Sandbox Code Playgroud)

在开发/测试期间禁用此配置类,或者确保在来自 MockMVC 等测试库的所有请求中设置适当的标头,否则您将破坏这些测试。

如果我有一些空闲时间,我会尝试让开箱即用的解决方案发挥作用,但现在,这将(必须)做到。


归档时间:

查看次数:

3512 次

最近记录:

7 年,5 月 前