使用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
相关产品推荐
相关产品推荐

