首页 > 解决方案 > 在反向代理后面,Spring Security 登录重定向到错误的端口

问题描述

我有以下配置:

我遇到的问题是成功登录后,Spring Security 构建的重定向 url 是https://server:8443/whatever. url 是正确的(它是根据初始保存的请求构建的),但端口除外。在此配置中,端口 8443 上没有运行任何内容。

我看到这发生在 Spring 的PortMapperImpl. 这里默认有两个映射:8080 -> 844380 -> 443.

如何覆盖PortMapperImpl或实现我自己的并强制 Spring 使用它?或者有没有不同的方法来解决这个问题?

标签: javaspringspring-security

解决方案


我找到了解决方案。在 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


推荐阅读