Spring Boot 3迁移后.csrf()与.requiresChannel()废弃替代方案咨询
Spring Boot 3.1.2 迁移:解决
csrf()和requiresChannel()废弃问题 废弃方法替代方案
1. csrf() 替代
原代码中.csrf().disable()属于旧版链式调用写法,Spring Security 6+(Spring Boot 3.x 对应版本)推荐使用lambda配置器方式,保持配置的类型安全性:
.csrf(csrf -> csrf.disable())
2. requiresChannel() 替代
requiresChannel()方法已被移除,替代方案是使用channel()配置器结合请求匹配器指定通道要求:
原代码段:
.requiresChannel() .antMatchers("/actuator/**") .requiresInsecure()
替换为:
.channel(channel -> channel .requestMatchers("/actuator/**") .requiresInsecure() )
额外注意:authorizeRequests() 也已废弃
原代码中的.authorizeRequests()同样属于废弃API,需替换为.authorizeHttpRequests(),这是Spring Security 6+的强制重构要求:
原代码段:
.authorizeRequests() .antMatchers("/api/v*/registration/**", "/register*", "/login", "/actuator/**").permitAll() .anyRequest().authenticated()
替换为:
.authorizeHttpRequests(auth -> auth .requestMatchers("/api/v*/registration/**", "/register*", "/login", "/actuator/**").permitAll() .anyRequest().authenticated() )
修改后的完整配置代码
@Configuration @EnableWebSecurity public class ApplicationSecurityConfig { private final ApplicationUserService applicationUserService; private final BCryptPasswordEncoder bCryptPasswordEncoder; public ApplicationSecurityConfig( ApplicationUserService applicationUserService, BCryptPasswordEncoder bCryptPasswordEncoder) { this.applicationUserService = applicationUserService; this.bCryptPasswordEncoder = bCryptPasswordEncoder; } @Bean protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http // 替代原csrf().disable()写法 .csrf(csrf -> csrf.disable()) // 替代原requiresChannel()配置逻辑 .channel(channel -> channel .requestMatchers("/actuator/**") .requiresInsecure() ) // 替代原authorizeRequests()配置 .authorizeHttpRequests(auth -> auth .requestMatchers("/api/v*/registration/**", "/register*", "/login", "/actuator/**").permitAll() .anyRequest().authenticated() ) .formLogin(form -> form .loginPage("/login") .usernameParameter("email") .permitAll() .defaultSuccessUrl("/", true) .failureUrl("/login-error") ) .logout(logout -> logout .logoutUrl("/logout") .clearAuthentication(true) .invalidateHttpSession(true) .deleteCookies("JSESSIONID", "Idea-2e8e7cee") .logoutSuccessUrl("/login") ); return http.build(); } @Bean public AuthenticationManager authenticationManager( AuthenticationConfiguration authenticationConfiguration) throws Exception { return authenticationConfiguration.getAuthenticationManager(); } @Bean public DaoAuthenticationProvider daoAuthenticationProvider() { DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); provider.setPasswordEncoder(bCryptPasswordEncoder); provider.setUserDetailsService(applicationUserService); return provider; } }
这些调整均为Spring Security 6.x的API重构内容,目的是提升配置代码的可读性与类型安全性,避免链式调用中的潜在歧义。
内容的提问来源于stack exchange,提问作者Alex_Pap
相关产品推荐
相关产品推荐

