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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 11:55:07