Spring Security 6.x中antMatchers无法解析问题求助(弃用WebSecurityConfigurerAdapter)
解决Spring Security 6.x中
antMatchers无法解析的问题 问题原因
你使用的Spring Security 6.1.3版本已彻底移除authorizeRequests()和antMatchers()方法——这类旧版API从Spring Security 5.8开始被标记为弃用,6.x版本直接删除了相关实现,因此IDE会提示无法解析方法。
修正后的SecurityConfig代码
替换为Spring Security 6.x推荐的authorizeHttpRequests()和requestMatchers()API即可:
import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.web.SecurityFilterChain; @EnableWebSecurity public class SecurityConfig { public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .csrf(csrf -> csrf.disable()) .authorizeHttpRequests(auth -> { auth.requestMatchers("/admin/**").hasRole("ADMIN") .requestMatchers("/user/**").hasRole("USER") .anyRequest().authenticated(); }) .httpBasic(); return http.build(); } }
额外说明
- 如需针对指定HTTP方法做请求匹配,可使用
requestMatchers(HttpMethod.GET, "/admin/**")形式,需提前导入org.springframework.http.HttpMethod包。 - 你的pom.xml中
spring-security-config指定了6.1.3版本,而spring-boot-starter-security会自动适配Spring Boot对应的Security版本,建议保持版本一致,避免依赖冲突。
内容的提问来源于stack exchange,提问作者Jules
相关产品推荐
相关产品推荐

