Spring Security 6.1+ 废弃API迁移遇错,求正确配置方案
Spring Security 6.1+(Spring Cloud 2023.0.1)配置迁移方案
针对你遇到的弃用错误,以下是符合6.1+版本规范的正确配置代码:
@Bean public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { http.csrf(csrf -> csrf.disable()) .authorizeHttpExchange(authz -> authz .pathMatchers("/api/**").permitAll() .anyExchange().authenticated() ) .oauth2Login(Customizer.withDefaults()) // 启用默认OAuth2登录流程,实现跳转登录页需求 .cors(cors -> cors.configurationSource(request -> { CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000")); configuration.setAllowedMethods(Arrays.asList("GET", "POST", "OPTIONS")); configuration.setAllowedHeaders(List.of("*")); return configuration; })); return http.build(); }
关键修改说明:
- CSRF配置:放弃
CsrfConfigurer::disable方法引用,改用lambda调用实例的disable()方法,解决"非静态方法不能在静态上下文引用"的错误。 - 授权规则:用
authorizeHttpExchange()替代弃用的authorizeExchange(),在lambda内部直接链式配置路径权限,不再需要and()衔接。 - OAuth2登录:用
oauth2Login(Customizer.withDefaults())替代弃用的oauth2Login(),通过Customizer.withDefaults()启用默认的OAuth2登录逻辑,满足跳转登录页的需求。 - CORS配置:将原链式调用改为lambda形式,直接在
cors()的参数中配置configurationSource,贴合新版本配置风格。
另外修正了原代码中的语法错误:Arrays.asList("http://localhost:3000")末尾缺失的闭合括号。
内容的提问来源于stack exchange,提问作者Peter Penzov
相关产品推荐
相关产品推荐

