Skip to content

Spring Security 6.0 升级:替代已弃用功能

问题描述

升级至 Spring Boot 3.0 和 Spring Security 6.0 时,开发者面临以下关键变化:

  • ⚠️ authorizeRequests() 方法已被弃用
  • antMatchers()mvcMatchers()regexMatchers() 方法彻底移除
  • @EnableGlobalMethodSecurity 注解不再可用

这些问题导致现有安全配置失效(如下图所示),需要迁移到新API:

解决方案

以下是完整的配置迁移方案:

1. 替换请求授权方法

核心变更

  • 使用 authorizeHttpRequests 代替弃用的 authorizeRequests
  • 使用 requestMatchers 替代移除的 antMatchers
java
@Bean
public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
    return httpSecurity
        .csrf(csrf -> csrf.disable())
        .authorizeHttpRequests(auth -> auth  // 替换为新的授权方法
            .requestMatchers("/token/**").permitAll()  // 使用requestMatchers
            .anyRequest().authenticated()
        )
        .sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
        .oauth2ResourceServer(spec -> spec.jwt(Customizer.withDefaults()))  // 更新后的JWT配置
        .httpBasic(Customizer.withDefaults())
        .build();
}

2. 替换方法安全注解

移除 @EnableGlobalMethodSecurity(prePostEnabled = true),替换为:

java
@Configuration
@EnableWebSecurity
@EnableMethodSecurity  // 简化的新注解,默认启用prePost
public class SecurityConfig {
    // 配置类内容
}

注意

@EnableMethodSecurity 自动启用了 @PreAuthorize@PostAuthorize 注解,无需显式设置 prePostEnabled = true

3. JWT 资源服务器配置更新

原配置中的 OAuth2ResourceServerConfigurer::jwt 已过时,替换为:

java
.oauth2ResourceServer(spec -> spec.jwt(Customizer.withDefaults()))

4. CSRF 禁用最佳实践

针对不同版本使用安全写法:

java
// Spring Security 6.0 写法
.csrf(csrf -> csrf.disable())

// Spring Security 6.1+ 推荐写法(避免弃用警告)
.csrf(AbstractHttpConfigurer::disable)

::: note 完整示例 整合所有变更的完整配置:

java
@Configuration
@EnableWebSecurity
@EnableMethodSecurity  // 替换后的注解
public class SecurityConfig {
    // 其他依赖注入...

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
        return httpSecurity
            .csrf(AbstractHttpConfigurer::disable)  // 推荐的CSRF禁用方式
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/token/**").permitAll()  // 更新的请求匹配方法
                .anyRequest().authenticated()
            )
            .sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .oauth2ResourceServer(spec -> spec.jwt(Customizer.withDefaults()))  // 更新后的OAuth2配置
            .httpBasic(Customizer.withDefaults())
            .build();
    }
    
    // 其他Bean定义...
}

:::

变更原理说明

  1. Lambda DSL优先
    Spring Security 6 全面转向函数式配置,提供更强的类型安全性和链式调用体验

  2. 方法安全粒度优化
    @EnableMethodSecurity 基于代理实现,支持更细粒度的权限控制

  3. URL匹配统一化
    requestMatchers() 整合原有多种匹配方式:

    java
    // 等效原antMatchers多种用法
    .requestMatchers("/public/**").permitAll()
    .requestMatchers(HttpMethod.POST, "/api/**").hasRole("ADMIN")

迁移注意事项

  1. 确保所有权限规则迁移后功能不变
  2. 测试@PreAuthorize等注解是否正常生效
  3. 检查所有自定义RequestMatcher的兼容性
  4. 更新Spring Security相关依赖到6.0+

通过以上迁移方案,您的应用将完全兼容Spring Security 6+ 最新API设计更简洁安全,长期维护成本显著降低