Spring Security 6.1中WebSecurityConfigurerAdapter已删除,如何重写configure方法?
Spring Security 5.7+(含6.x)替代WebSecurityConfigurerAdapter的配置方案
WebSecurityConfigurerAdapter类在Spring Security 5.7版本已被移除,6.x版本彻底不再支持,此前通过继承该类重写configure(HttpSecurity)方法的配置方式已无法使用。
旧版配置方式(已废弃)
public class MySecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/public/**").permitAll() .antMatchers("/admin/**").hasRole("ADMIN") .anyRequest().authenticated() .and() .formLogin(); } }
新版配置方案(推荐)
通过定义SecurityFilterChain类型的Bean来实现权限配置,示例代码如下:
@Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests((requests) -> requests .requestMatchers("/user/student/**") .hasRole("student") .requestMatchers("/user/admin/**") .hasAnyAuthority("admin:add") .requestMatchers("/user/teacher/**") .hasRole("teacher") .anyRequest() .authenticated() ); http.formLogin(AbstractAuthenticationFilterConfigurer::permitAll); return http.build(); }
关键变化点
- 原
http.authorizeRequests()已被废弃,替换为http.authorizeHttpRequests() - 路径匹配方法
antMatchers/mvcMatchers统一替换为requestMatchers - 核心配置逻辑与旧版基本一致,仅API名称调整以适配新的编程模型
内容的提问来源于stack exchange,提问作者coding_lover
相关产品推荐
相关产品推荐

