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

使用Spring Boot Security Filter Chain替代WebSecurityConfigurerAdapter时出错

问题1:SecurityFilterChain中httpSecurity未识别及return语句错误

你的代码存在笔误:方法参数为HttpSecurity httpSecurity,但最后返回语句使用了未定义的http,需改为httpSecurity.build()。修正后的代码如下:

@Bean
public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
    httpSecurity.csrf()
            .disable()
            .authorizeRequests()
            .antMatchers(HttpMethod.DELETE)
            .hasRole("ADMIN")
            .antMatchers("/admin/**")
            .hasAnyRole("ADMIN")
            .antMatchers("/user/**")
            .hasAnyRole("USER", "ADMIN")
            .antMatchers("/login/**")
            .anonymous()
            .anyRequest()
            .authenticated()
            .and()
            .httpBasic()
            .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

    return httpSecurity.build(); // 修正为方法参数名httpSecurity
}

同时请确认已正确导入org.springframework.security.config.annotation.web.builders.HttpSecurity类,避免因导入错误导致的未识别问题。

问题2:WebSecurityCustomizer中antMatchers报错

该报错常见原因及解决方式如下:

  • 导入错误:确保已导入org.springframework.security.web.util.matcher.AntPathRequestMatcher相关类,避免误导入其他包下的同名方法。
  • 语法格式问题:检查代码中的引号是否为正常双引号("),避免使用转义字符(如")导致语法错误。修正后的标准写法如下:
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
    return web -> web.ignoring().antMatchers("/ignore1", "/ignore2");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 07:05:24