在反向代理后面需要使用Spring Security的https

Ser*_*sta 12 java https reverse-proxy spring-security

我有一个使用Spring Security保护的Spring MVC应用程序.大多数应用程序使用简单的http来节省资源,但是一小部分处理更多机密信息并需要https频道.

摘自security-config.xml:

<sec:http authentication-manager-ref="authenticationManager" ... >
    ...
    <sec:intercept-url pattern="/sec/**" requires-channel="https"/>
    <sec:intercept-url pattern="/**" requires-channel="http"/>
</sec:http>
Run Code Online (Sandbox Code Playgroud)

一切正常,直到我们决定将其迁移到主服务器,其中应用程序服务器在反向代理后面运行.现在,HTTPS由反向代理处理,应用程序服务器只能看到HTTP请求,并且不允许访问/sec/**层次结构.

经过一些研究,我发现代理添加了一个X-Forwarded-Proto: https(*),但在Spring Security HttpServletRequest.isSecure()中用于确定所提供的通道安全性(从SecureChannelProcessorjavadoc中提取)

如何告诉Spring Security X-Forwarded-Proto: https标头足以满足安全请求?

我知道我可以在代理配置上报告该部分,但代理管理员确实不喜欢该解决方案,因为代理背后有许多应用程序,并且配置可能会增长到不可管理的状态.

我目前正在使用带有XML配置的Spring Security 3.2,但我已准备好接受基于Java配置和/或更新版本的答案.

(*)当然,代理如果它在传入请求中存在则删除标题,因此应用程序可以对它充满信心.

Ser*_*sta 19

NeilMcGuigan的答案的后续种类表明该解决方案是servlet容器端.

Tomcat甚至更好.有一个专用于屏蔽反向代理的副作用的阀门.从远程IP阀门的 Tomcat文档中提取:

该阀的另一个特征是用代理或负载均衡器通过请求头(例如"X-Forwarded-Proto")提供的方案替换明显的方案(http/https),服务器端口和request.secure.

阀门配置示例:

<Valve className="org.apache.catalina.valves.RemoteIpValve"
    internalProxies="192\.168\.0\.10|192\.168\.0\.11"
    remoteIpHeader="x-forwarded-for" proxiesHeader="x-forwarded-by"
    protocolHeader="x-forwarded-proto" />
Run Code Online (Sandbox Code Playgroud)

这种方式没有应用程序本身的其他配置,Request.isSecure()如果请求包含头字段,则调用将返回true X-Forwarded-Proto=https.

我曾想过另外两种可能性,但最终还是要优先考虑一种:

  • 使用在Spring Security之前处于活动状态的过滤器ChannelProcessingFilterHttpServletRequestWrapper覆盖请求,并使用覆盖isSecure()来处理X-Forwarded-Proto标头 - 需要编写和测试过滤器和包装器
  • 使用Spring BeanPostProcessor来查找ChannelProcessingFilter并手动注入一个ChannelDecisionManager能够考虑X-Forwarded-Proto头部 - 真的太低级别

  • @Giordano:当我问这个问题时,帮我找到这个问题的答案是Neil的答案.这就是我接受它的原因:-) - 但因为它没有我想要的那么完整,所以我添加了这个. (2认同)

Rom*_*nko 10

Spring Boot使它变得非常简单(至少对于嵌入式Tomcat)。

1.将以下行添加到application.properties:

server.use-forward-headers=true
server.tomcat.remote-ip-header=x-forwarded-for
server.tomcat.protocol-header=x-forwarded-proto
Run Code Online (Sandbox Code Playgroud)

2.对您的HttpSecurity配置执行以下技巧。

// final HttpSecurity http = ...
// Probably it will be in your `WebSecurityConfigurerAdapter.configure()`

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

来源是Spring Boot参考指南

84.3在代理服务器上运行时启用HTTPS

  • 也适用于嵌入式 Jetty。将此用于面向 Internet 的 AWS ALB HTTPS (2认同)

Nei*_*gan 5

如果您的站点是HTTPS并且您正在另一个处理TLS终止的系统后面运行Apache Tomcat,您可以告诉Tomcat"假装"它正在处理TLS终止.

这使得request.isSecure()回归true;

为此,您需要添加secure="true"到Connector配置中server.xml.

https://tomcat.apache.org/tomcat-7.0-doc/config/http.html

另请参见scheme属性.