You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 3 + Security 6多SecurityFilterChain配置异常求助

问题分析与解决方案

问题根源

第一种配置失效原因

第一个SecurityFilterChain未配置securityMatcher,Spring Security会默认让它匹配所有请求。由于它的@Order(1)优先级最高,所有请求(包括/downloadRedirect/**)都会被它先处理,而它的规则是anyRequest().authenticated(),导致第三个过滤器完全没有执行机会,自定义的DownloadRedirectMatcher自然不生效。

第二种配置的404原因

给第一个过滤器设置securityMatcher("/customer*")后,它只会匹配/customer开头的路径,但OAuth2登录流程依赖的核心端点(比如/oauth2/authorization/**、/login/oauth2/code/**)不在这个匹配范围内。当访问/customer/触发登录重定向时,登录相关请求找不到对应的过滤器处理,直接返回404。

正确配置方案

调整两个过滤器的securityMatcher,确保每个过滤器只处理自己负责的路径,同时覆盖OAuth2登录所需的端点:

@Bean
@Order(1)
public SecurityFilterChain clientFilterChain(HttpSecurity http) throws Exception {
    // 明确指定该过滤器处理的路径:根路径、客户路径、OAuth2登录相关端点
    http.securityMatcher("/", "/customers/**", "/oauth2/authorization/**", "/login/oauth2/code/**")
        .authorizeHttpRequests(authorize -> authorize
                .requestMatchers("/").permitAll()
                .anyRequest().authenticated()
        )
        .oauth2Login(withDefaults());

    return http.build();
}

@Bean
@Order(2)
public SecurityFilterChain publicDownloadRedirectFilter(HttpSecurity http) throws Exception {
    http.securityMatcher("/downloadRedirect/**")
            .authorizeHttpRequests(authorize -> authorize
                    .requestMatchers(new DownloadRedirectMatcher()).permitAll()
                    .anyRequest().authenticated()
            );

    return http.build();
}

关键说明

  1. 路径匹配修正:把原代码中的/customers**改为/customers/**,符合Spring AntPathMatcher的语法(**用于匹配多级子路径)。
  2. OAuth2端点覆盖:第一个过滤器的securityMatcher必须包含/oauth2/authorization/**和/login/oauth2/code/**,这是OAuth2登录流程的核心端点,确保登录跳转和回调能被正确处理。
  3. 过滤器顺序:第二个过滤器的@Order设为2,确保在第一个过滤器之后执行,且仅处理/downloadRedirect/**路径。

内容的提问来源于stack exchange,提问作者saavedrah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 23:20:06