Spring 6迁移:Spring Security的CORS与匹配器配置迁移咨询
Spring 6 中 CORS 与权限配置的迁移方案
核心变化说明
Spring Security 6 彻底摒弃了旧的.and()链式衔接方式,统一采用Lambda 配置风格,同时antMatchers已被废弃,推荐使用requestMatchers来匹配请求路径。
迁移后的完整代码
@Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http // CSRF 配置保持已完成的Lambda写法 .csrf(csrf -> csrf.disable()) // CORS 配置:用Lambda直接指定配置源,无需.and() .cors(cors -> cors.configurationSource(corsConfigurationSource())) // 权限配置:使用requestMatchers替代antMatchers,Lambda内部完成规则定义 .authorizeHttpRequests(auth -> auth .requestMatchers("/**").permitAll() .requestMatchers("/api/**").authenticated() // 建议保留anyRequest()兜底,避免遗漏路径权限 .anyRequest().authenticated() ) // 过滤器配置直接链式调用,无需.and() .addFilterBefore(new AwsCognitoJwtAuthFilter(awsCognitoIdTokenProcessor), UsernamePasswordAuthenticationFilter.class); return http.build(); }
关键迁移点拆解
CORS 配置:
旧写法中.cors().configurationSource(...).and()的.and()可以完全去掉,直接用.cors(cors -> cors.configurationSource(...))的Lambda形式完成配置,这是Spring Security 6的标准写法。权限请求配置:
- 替换
antMatchers为requestMatchers:两者功能类似,但requestMatchers支持更灵活的匹配方式(比如MVC路径匹配、媒体类型匹配等),是Spring Security 6的推荐API。 - 用Lambda包裹所有权限规则:
authorizeHttpRequests(auth -> auth...)内部直接链式定义所有路径的权限,不再需要.and()来衔接不同的规则。
- 替换
补充说明
如果你的corsConfigurationSource()方法是自定义的CORS配置(比如允许特定Origin、Header等),这个方法的实现不需要修改,Spring Security 6完全兼容旧的CorsConfigurationSource接口实现。
内容的提问来源于stack exchange,提问作者HeronAlgoSearch
相关产品推荐
相关产品推荐

