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

使用permitAll()和web.ignoring()无法绕过Spring Security过滤器链处理特定端点

解决Spring Security过滤器链仅作用于指定路径的问题

问题分析

你当前的配置存在两个核心问题:

  1. permitAll() 仅会跳过授权校验,但请求仍然会完整经过Spring Security的过滤器链(包括DisableEncodeUrlFilter、CsrfFilter等),这和你要完全绕过过滤器链的需求不符。
  2. WebSecurity.ignoring().antMatchers("/myapi/*") 中的路径匹配规则不对:/*仅能匹配/myapi下的一级路径(比如/myapi/abc),无法匹配多级子路径(比如/myapi/abc/123),导致部分请求依然进入过滤器链。

解决方案

1. 修正路径匹配规则,完全绕过/myapi路径

将WebSecurityCustomizer中的路径改为/myapi/**,确保匹配/myapi下的所有子路径:

@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
    return (web) -> web.ignoring().antMatchers("/myapi/**");
}

2. 限制SecurityFilterChain仅作用于/saml路径

在HttpSecurity配置中添加securityMatcher(),指定当前过滤器链仅处理/saml/**路径的请求,其他路径直接跳过该过滤器链:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
        // 仅对/saml/**路径应用此过滤器链
        .securityMatcher("/saml/**")
        .addFilterBefore(new SamlExtensionUrlForwardingFilter(), DisableEncodeUrlFilter.class)
        .authorizeHttpRequests((authorize) -> authorize
                    // 该过滤器链下的所有请求都需要认证
                    .anyRequest().authenticated()
                )
        .saml2Login()
                .successHandler(new MyAuthenticationSuccessHandler());
    return http.build();
}

3. 移除冗余配置

删除HttpSecurity中.antMatchers("/myapi/*").permitAll()的配置,因为已经通过WebSecurity.ignoring()和securityMatcher()完全排除了/myapi路径的Security处理,该配置已无意义。

补充说明(针对Spring Security 6.x版本)

如果使用Spring Security 6.x,antMatchers已被标记为过时,建议替换为requestMatchers:

// WebSecurityCustomizer
return (web) -> web.ignoring().requestMatchers("/myapi/**");

// HttpSecurity
.authorizeHttpRequests((authorize) -> authorize
    .requestMatchers("/saml/**").authenticated()
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 21:50:33