
本文详解 Spring Security 5.x 到 6.1.x 的核心迁移要点,涵盖 authorizeRequests() 替换为 authorizeHttpRequests()、WebSecurityConfigurerAdapter 废弃后的配置重构、csrf()/cors() 等 DSL 更新语法,并提供可直接运行的配置示例与常见 403 错误排查方案。
本文详解 spring security 5.x 到 6.1.x 的核心迁移要点,涵盖 `authorizerequests()` 替换为 `authorizehttprequests()`、`websecurityconfigureradapter` 废弃后的配置重构、`csrf()`/`cors()` 等 dsl 更新语法,并提供可直接运行的配置示例与常见 403 错误排查方案。
Spring Security 6.1.x(基于 Spring Framework 6+)引入了全面重构的安全配置模型,彻底移除了长期被广泛使用的 WebSecurityConfigurerAdapter,并采用函数式、不可变的 SecurityFilterChain Bean 配置方式。若你仍沿用 Spring Security 5.x 的写法(如 http.authorizeRequests()),将导致编译失败或运行时 403 错误——这是因为旧方法已被标记为 @Deprecated 并在 6.0+ 中完全移除。
✅ 正确迁移步骤
1. 替换授权配置 DSL
authorizeRequests() → authorizeHttpRequests(),且必须使用 Lambda 表达式定义匹配规则:
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authz -> authz
.requestMatchers("/", "/public/**").permitAll() // ✅ 明确指定路径模式
.anyRequest().authenticated() // ✅ 默认兜底策略(重要!)
)
.cors(Customizer.withDefaults()) // ✅ 启用 CORS(需配合 CorsConfigurationSource)
.csrf(AbstractHttpConfigurer::disable) // ✅ 显式禁用 CSRF(注意:不再支持 .disable() 链式调用)
.httpBasic(Customizer.withDefaults()); // ✅ 启用 HTTP Basic(可选)
return http.build(); // ⚠️ 必须显式调用 build()
}? 关键细节:
anyRequest().authenticated()是必需的“兜底规则”,否则未显式匹配的请求将默认拒绝(返回 403)。requestMatchers("/**")虽可覆盖全部路径,但会绕过安全校验,仅适用于完全公开的 API;生产环境应遵循最小权限原则,分层配置。
2. 移除所有 @EnableWebSecurity 的过时用法
Spring Security 6+ 不再需要 @EnableWebSecurity 注解(它已隐式启用),但保留它不会报错;建议移除以保持代码简洁。
3. CORS 配置需额外声明(如需跨域)
仅 .cors(Customizer.withDefaults()) 不足以生效,还需提供 CorsConfigurationSource Bean:
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("https://example.com", "http://localhost:3000"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}4. 注意其他常见变更
-
antMatchers()/mvcMatchers()已统一为requestMatchers()(支持 AntPath、MvcPath、Regex 多种匹配器)。 -
formLogin()、logout()等模块均改用Customizer.withDefaults()或函数式配置。 -
AuthenticationManager需显式定义 Bean(若使用自定义认证逻辑),不再由框架自动创建。
⚠️ 常见陷阱与调试建议
-
403 错误根源:未配置
anyRequest().authenticated()或路径匹配顺序错误(如"/api/**"在"/**"之后将永不触发)。 -
CSRF 报错:若前端未携带
X-XSRF-TOKEN,又未禁用 CSRF,则 POST/PUT/DELETE 请求会失败;前后端需协同处理 Token 流程,或明确禁用(如 REST API 场景)。 -
依赖版本对齐:确保
spring-boot-starter-security与 Spring Boot 3.x(即 Spring Framework 6.x)版本严格匹配,避免混合引入 5.x 的 transitive 依赖。
完成上述调整后,你的安全配置即可兼容 Spring Security 6.1.x,并具备更好的类型安全性和可读性。建议同步查阅官方 Migration Guide 获取全量变更清单。

















