WebSecurityConfigurerAdapter弃用后,如何将DaoAuthenticationProvider注入AuthenticationManager?
解决方案:在Spring Security新版本中注入自定义DaoAuthenticationProvider
核心方案
在Spring Security弃用WebSecurityConfigurerAdapter的新版本中,无需手动将自定义Provider绑定到AuthenticationManager,只需保证你的DaoAuthenticationProvider是Spring容器中的有效Bean,框架会自动完成注册关联。
完整代码示例
- 保留自定义的
DaoAuthenticationProviderBean定义(和旧版本逻辑一致):
@Bean public DaoAuthenticationProvider daoAuthenticationProvider(BCryptPasswordEncoder bCryptPasswordEncoder, ApplicationUserService applicationUserService) { DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); provider.setPasswordEncoder(bCryptPasswordEncoder); provider.setUserDetailsService(applicationUserService); return provider; }
- 你的
AuthenticationManagerBean定义无需修改:
@Bean public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception { return authenticationConfiguration.getAuthenticationManager(); }
- 移除旧版本中重写的
configure(AuthenticationManagerBuilder)方法,新版本不再需要手动配置这一步。
原理说明
Spring Security 5.7+采用了基于组件的配置模式,AuthenticationConfiguration会自动扫描Spring上下文中所有类型为AuthenticationProvider的Bean,并将它们自动注册到AuthenticationManager的构建流程中。只要你的自定义DaoAuthenticationProvider被声明为Bean,就会被自动纳入AuthenticationManager的认证逻辑链。
内容的提问来源于stack exchange,提问作者Alex_Pap
相关产品推荐
相关产品推荐

