Spring 6.1.1中SecurityFilterChain相关方法废弃,求代码修复
修复Spring Security 6+中废弃的SecurityFilterChain方法
Spring Security 6.x版本对配置API做了优化,废弃了旧的链式and()调用方式,转而推荐使用lambda DSL风格来配置,以下是修复后的代码:
import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.web.SecurityFilterChain; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import java.util.List; @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { return http // 配置CORS,使用默认配置可替换为cors(Customizer.withDefaults()) .cors(cors -> cors.configurationSource(corsConfigurationSource())) // 禁用CSRF .csrf(csrf -> csrf.disable()) // 统一配置请求授权规则 .authorizeHttpRequests(auth -> auth .requestMatchers("/register").permitAll() .requestMatchers("/users").hasAnyAuthority("USER", "ADMIN") // 默认规则:所有未匹配的请求都需要认证 .anyRequest().authenticated()) // 启用默认表单登录 .formLogin(Customizer.withDefaults()) .build(); } // 自定义CORS配置(按需添加,不需要可删除) @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration config = new CorsConfiguration(); config.setAllowedOrigins(List.of("http://localhost:3000")); // 替换为实际允许的前端域名 config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS")); config.setAllowedHeaders(List.of("*")); config.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", config); return source; } }
关键修改说明:
- cors():旧无参方法被废弃,现在需要传入
Customizer。如果不需要自定义CORS规则,直接用cors(Customizer.withDefaults())即可;需要自定义则通过lambda指定配置源。 - csrf配置:从链式调用
csrf().disable()改为lambda写法csrf(csrf -> csrf.disable()),更符合新版本的配置风格。 - authorizeHttpRequests():废弃了无参调用,改用lambda集中管理所有授权规则,无需多次调用
authorizeHttpRequests()和and(),同时添加anyRequest().authenticated()作为默认安全规则,避免未授权的请求被放行。 - formLogin():旧无参方法废弃,使用
formLogin(Customizer.withDefaults())启用默认表单登录,如需自定义登录页面、成功处理器等,可替换为lambda配置:formLogin(login -> login.loginPage("/login").defaultSuccessUrl("/home"))。 - 移除and():新版本lambda DSL不需要用
and()来连接不同配置块,每个配置项独立通过lambda配置,代码结构更清晰。
内容的提问来源于stack exchange,提问作者naomie lutete
相关产品推荐
相关产品推荐

