繁体   English   中英

在反向代理之后,Spring Security登录重定向到错误的端口

[英]Behind a Reverse Proxy, Spring Security Login Redirects to Wrong Port

我有以下配置:

  • 启用弹簧安全性的Web应用程序,具有基于表单的登录名
    • 它运行在http端口8080上; 没有https
  • 在前面运行的反向代理
    • 它在端口443上运行,并在此处终止SSL
    • 代理设置适当的标头( HostX-Forwarded-Proto

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

我看到这是在Spring的PortMapperImpl发生的。 默认情况下,这里有两个映射: 8080 -> 844380 -> 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设置为的端口。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM