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

Spring Security中antMatchers方法报错,咨询公开URL的替代方案

Spring Boot中Spring Security公开指定URL的解决方案

先修复你当前的代码错误

你遇到的antMathcers方法未定义错误,本质是拼写错误——正确方法名是antMatchers,修正后代码即可正常运行:

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeRequests()
            .antMatchers("/api/public").permitAll() // 修正拼写:Mathcers → Matchers
            .anyRequest().authenticated()
            .and()
            .formLogin().permitAll()
            .and()
            .logout().permitAll();
        
        return http.build();
    }
}

新版Spring Security推荐的替代实现方式

1. Lambda风格配置(Spring Security 5.2+ 官方推荐)

这种写法摒弃了繁琐的and()链式调用,代码更简洁易读:

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .csrf(csrf -> csrf.disable())
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/public").permitAll()
                .anyRequest().authenticated()
            )
            .formLogin(form -> form.permitAll())
            .logout(logout -> logout.permitAll());
        
        return http.build();
    }
}

2. 使用requestMatchers替代antMatchers

新版Spring Security更推荐requestMatchers,它支持Ant风格路径、正则表达式、MVC路径等多种匹配规则,兼容性更强:

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeHttpRequests()
            .requestMatchers("/api/public").permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin().permitAll()
            .and()
            .logout().permitAll();
        
        return http.build();
    }
}

3. 批量公开多组URL

如果需要一次性公开多个路径,可直接传入多个参数,或使用通配符:

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeHttpRequests(auth -> auth
                // 公开单个路径、多个路径、静态资源路径
                .requestMatchers("/api/public", "/api/guest/**", "/static/**").permitAll()
                .anyRequest().authenticated()
            )
            .formLogin().permitAll()
            .logout().permitAll();
        
        return http.build();
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 05:34:58