java - 在反向代理后面,Spring Security 登录重定向到错误的端口
问题描述
我有以下配置:
- 具有基于表单的登录的启用 spring-security 的 Web 应用程序
- 这在 http 端口 8080 上运行;没有 https
- 前面运行的反向代理
- 这在端口 443 上运行并在此处终止 SSL
- 代理设置适当的标头 (
Host
,X-Forwarded-Proto
)
我遇到的问题是成功登录后,Spring Security 构建的重定向 url 是https://server:8443/whatever
. url 是正确的(它是根据初始保存的请求构建的),但端口除外。在此配置中,端口 8443 上没有运行任何内容。
我看到这发生在 Spring 的PortMapperImpl
. 这里默认有两个映射:8080 -> 8443
和80 -> 443
.
如何覆盖PortMapperImpl
或实现我自己的并强制 Spring 使用它?或者有没有不同的方法来解决这个问题?
解决方案
我找到了解决方案。在 Spring Java 配置中:
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Value("${server.port}")
private int serverPort;
@Value("${security.sslRedirectPort}")
private int sslRedirectPort;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.[the usual request matchers, authorizeRequests, etc]
.and()
.requestCache().requestCache(requestCache());
}
private PortMapper portMapper() {
PortMapperImpl portMapper = new PortMapperImpl();
Map<String, String> mappings = Maps.newHashMap();
mappings.put(Integer.toString(serverPort), Integer.toString(sslRedirectPort));
portMapper.setPortMappings(mappings);
return portMapper;
}
private RequestCache requestCache() {
HttpSessionRequestCache requestCache = new HttpSessionRequestCache();
PortResolverImpl portResolver = new PortResolverImpl();
portResolver.setPortMapper(portMapper());
requestCache.setPortResolver(portResolver);
return requestCache;
}
}
这里发生了什么事:
- 我正在使用现有
server.port
设置来注入 http 端口(默认情况下,这是春季的 8080) - 我正在创建一个名为
security.sslRedirectPort
. 将此属性设置为您希望它在文件中重定向到的任何内容application.yaml
。 - 我创建了一个自定义
RequestCache
并将其插入到 spring 安全配置中。在这个自定义的 RequestCache 中,我PortResolver
在其上设置了 和PortMapper
,然后相应地设置了映射值。
现在,当我运行时,登录后我会得到一个正确的重定向 url,端口设置为我设置的任何值security.sslRedirectPort
。
推荐阅读
- r - r data.table 根据条件选择行
- android - Android - 如何将本地房间数据库与在线 mysql 数据库同步?
- augmented-reality - 编码扫描和识别像 ARKit 这样的 3D 对象?
- android - VpnService:更改允许的应用程序?
- android - Android统一照片质量
- solr - solr 7.3.0 授权在没有 zookeeper 的情况下不起作用
- c# - 为什么要制作List
.AddRange 方法是一个通用的方法对性能不利吗? - javascript - React Native - 在自定义应用程序中启动 Google 地图导航
- javascript - 动画 4 个 div 框仅动画 2 而不是 4
- java - 手机正则表达式