Spring Security 5.7 升级到 6.0 后 API 鉴权配置差异有哪些?

文章导读
Spring Security 6.0 移除了 WebSecurityConfigurerAdapter 类,API 鉴权配置必须改为通过 SecurityFilterChain Bean 定义。请求匹配方法从 antMatchers 变更为 requestMatchers,且不再支持继承配置类的方式。
📋 目录
  1. 快速处理思路
  2. 为什么会这样
  3. 分步处理
  4. 怎么验证是否生效
  5. 常见坑
  6. 常见问题
  7. 参考来源
A A

Spring Security 6.0 移除了 WebSecurityConfigurerAdapter 类,API 鉴权配置必须改为通过 SecurityFilterChain Bean 定义。请求匹配方法从 antMatchers 变更为 requestMatchers,且不再支持继承配置类的方式。

先说结论:Spring Security 6.0 强制使用组件化配置,旧版继承适配器的写法无法编译通过。

  • 适合:Spring Boot 3.x 项目或主动升级 Spring Security 6.x 的场景
  • 重点看:SecurityFilterChain Bean 定义和 requestMatchers 方法替换
  • 别忽略:AuthenticationManager 的获取方式需改为注入 AuthenticationConfiguration

快速处理思路

由于是 Java 配置变更,不涉及 shell 命令,直接修改配置类代码结构。

// 旧版 5.x 写法
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/api/**").authenticated();
    }
}
// 新版 6.x 写法
@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests().requestMatchers("/api/**").authenticated();
        return http.build();
    }
}

为什么会这样

官方为了鼓励开发者使用基于组件的安全配置,在 5.7.0-M2 版本中将 WebSecurityConfigurerAdapter 标记为过期,并在 6.0 版本中完全移除。

分步处理

1. 移除配置类对 WebSecurityConfigurerAdapter 的继承关系。

2. 新建返回类型为 SecurityFilterChain 的 Bean 方法,参数注入 HttpSecurity。

3. 将 authorizeRequests 改为 authorizeHttpRequests,antMatchers 改为 requestMatchers。

4. 若需获取 AuthenticationManager,注入 AuthenticationConfiguration 并调用 getAuthenticationManager 方法。

怎么验证是否生效

启动项目观察日志,确认无 Bean 定义冲突或类找不到错误。访问受保护接口,验证是否触发登录或返回 401 状态码。

Spring Security 5.7 升级到 6.0 后 API 鉴权配置差异有哪些?

常见坑

1. 静态资源忽略配置失效:旧版 configure(WebSecurity web) 方法移除,需改为定义 WebSecurityCustomizer Bean。

2. 密码编码器缺失:6.x 版本不再默认提供 PasswordEncoder Bean,需手动定义 BCryptPasswordEncoder。

3. CSRF 配置变更:默认启用 CSRF,前后端分离项目需显式关闭 csrf().disable()。

常见问题

Spring Boot 2.7 能用 Spring Security 6 吗?

不建议混用,Spring Boot 2.7 默认对应 Spring Security 5.7,Spring Boot 3.x 才默认对应 Spring Security 6.x。

自定义登录过滤器如何获取 AuthenticationManager?

不能在配置类中直接重写方法获取,需通过 AuthenticationConfiguration 工具类获取 Bean。

参考来源

1. CSDN 博客《Spring Security6 全新写法,大变样!》

2. 博客园《新旧版本 SpringSecurity 使用对比》

3. 技术文章《SpringBoot 升级到 3.4.3,Spring Security 从 5.x 升级到 6.x,原来有这么多坑》