Spring Boot中替换已弃用的WebSecurityConfigurerAdapter方案求助
替换WebSecurityConfigurerAdapter的Spring Security配置方案
以下是适配Spring Security 5.7+(弃用WebSecurityConfigurerAdapter后的版本)的配置代码,完全替代你原有的实现:
@Configuration @EnableWebSecurity public class WebSecurityConfig { @Bean public UserDetailsService userDetailsService() { return new UserDetailsServiceImpl(); } @Bean public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean public DaoAuthenticationProvider authenticationProvider() { DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); authProvider.setUserDetailsService(userDetailsService()); authProvider.setPasswordEncoder(passwordEncoder()); return authProvider; } @Bean public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception { return authConfig.getAuthenticationManager(); } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests() .anyRequest().authenticated() .and() .formLogin() .permitAll() .and() .logout() .permitAll(); return http.build(); } }
关键改动说明
- 移除继承关系:不再继承
WebSecurityConfigurerAdapter,改用基于Bean的配置模式(官方推荐的弃用后替代方案)。 - HTTP安全配置迁移:用
SecurityFilterChainBean替代原configure(HttpSecurity)方法,注意使用authorizeHttpRequests()替代已弃用的authorizeRequests()。 - 认证管理器配置:通过
AuthenticationConfiguration获取AuthenticationManager,原DaoAuthenticationProvider作为Bean会自动被注册到认证管理器中,无需手动调用配置方法。 - 原有核心Bean保留:
UserDetailsService、BCryptPasswordEncoder、DaoAuthenticationProvider的定义逻辑完全保留,功能与之前一致。
可选扩展
如果需要手动构建AuthenticationManager(而非依赖AuthenticationConfiguration),可以替换成以下实现:
@Bean public AuthenticationManager authenticationManager() { DaoAuthenticationProvider authProvider = authenticationProvider(); return new ProviderManager(authProvider); }
内容的提问来源于stack exchange,提问作者LeThanhTuan
相关产品推荐
相关产品推荐

