首页 > 解决方案 > Spring Security:如何设置自定义 PortMapper?

问题描述

我的应用程序同时监听 HTTP 和 HTTPS 端口。HTTP 通道仅对几个客户端可用,所有其他客户端在尝试访问不安全的通道时都必须重定向到安全通道 (HTTPS)。

问题是用于重定向的 HTTPS 端口,出于充分的理由,我根据应用程序属性自行启动连接器。默认端口映射实现不知道该配置PortMapperImpl,因此它始终返回4438443忽略应用程序正在侦听的实际端口。

到目前为止,我已经找到了这个;它有效,但看起来真的很难看:

@Configuration
class MySecurityAdapter extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
            .requiresChannel()
            .requestMatchers(/* some matchers */)
            .requiresSecure()
            .and()
            .setSharedObject(PortMapper.class, myPortMapper());
    }
    @Bean
    PortMapper myPortMapper() { return new MyPortMapper(); }
}

我正在使用标准的 Servlet API,因此我无法从似乎包含ServerHttpSecurity端口映射器的显式设置的位置中受益。

设置自定义端口映射器的正确方法是什么?它有什么优雅的吗?

标签: javaspringspring-security

解决方案


portMapper()servlet API 还允许使用该方法设置端口映射器。

在这种情况下,您可以使用以下配置

httpSecurity
        .requiresChannel()
            .requestMatchers(/* some matchers */)
            .requiresSecure()
            .and()
        .portMapper()
            .portMapper(new MyPortMapper());

推荐阅读