首页 > 解决方案 > SecurityConfig [Spring boot version 2.5.x]:为 ServerHttpSecurity 添加过滤器,仅用于安全 url

问题描述

我正在尝试为 ServerHttpSecurity 添加过滤器,并且我想跳过白名单中的 URL 过滤器,但过滤器适用于所有内容,如何避免这种情况

@Configuration
@EnableWebFluxSecurity
public class SecurityConfig {

    private static final String[] AUTH_WHITELIST = {
            ...
    };

    @Autowired
    private JsonWebTokenParser<Claims> jwtParser;

    @Bean
    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {

        AuthenticationFilter authenticationFilter = new AuthenticationFilter(jwtParser);

        http.authorizeExchange().pathMatchers(AUTH_WHITELIST).permitAll().anyExchange().authenticated()
            .and().cors().and().csrf().disable()
            .addFilterAfter(authenticationFilter, SecurityWebFiltersOrder.AUTHORIZATION);

        return http.build();
    }
}

标签: javaspring-bootspring-securityspring-cloud-gateway

解决方案


我猜你的意思是你不想通过过滤器来列入白名单的路径?

制作 2 个 Bean,其中一个处理您的白名单,另一个处理安全,并添加一个 securityMatcher。

Kotlin 示例,但同样适用于 Java

    @Bean
    @Order(1)
    fun whitelistWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
        return http
            .securityMatcher(pathMatchers(AUTH_WHITELIST))
            .authorizeExchange()
            .pathMatchers(AUTH_WHITELIST).permitAll()
            .and().build()
    }

    @Bean
    @Order(2)
    fun otherWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
        return http
            .securityMatcher(pathMatchers(/*set whatever you need here*/))
            .authorizeExchange()
            .pathMatchers(/*set whatever you need here (same as above)*/).authenticated()
            .and().cors().and().csrf().disable()
            .addFilterAfter(authenticationFilter, SecurityWebFiltersOrder.AUTHORIZATION)
            .build()
    }

推荐阅读