You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WebSecurityConfigurerAdapter弃用后,如何将DaoAuthenticationProvider注入AuthenticationManager?

解决方案:在Spring Security新版本中注入自定义DaoAuthenticationProvider

核心方案

在Spring Security弃用WebSecurityConfigurerAdapter的新版本中,无需手动将自定义Provider绑定到AuthenticationManager,只需保证你的DaoAuthenticationProvider是Spring容器中的有效Bean,框架会自动完成注册关联。

完整代码示例

  1. 保留自定义的DaoAuthenticationProvider Bean定义(和旧版本逻辑一致):
@Bean
public DaoAuthenticationProvider daoAuthenticationProvider(BCryptPasswordEncoder bCryptPasswordEncoder, ApplicationUserService applicationUserService) {
    DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
    provider.setPasswordEncoder(bCryptPasswordEncoder);
    provider.setUserDetailsService(applicationUserService);
    return provider;
}
  1. 你的AuthenticationManager Bean定义无需修改:
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
    return authenticationConfiguration.getAuthenticationManager();
}
  1. 移除旧版本中重写的configure(AuthenticationManagerBuilder)方法,新版本不再需要手动配置这一步。

原理说明

Spring Security 5.7+采用了基于组件的配置模式,AuthenticationConfiguration会自动扫描Spring上下文中所有类型为AuthenticationProvider的Bean,并将它们自动注册到AuthenticationManager的构建流程中。只要你的自定义DaoAuthenticationProvider被声明为Bean,就会被自动纳入AuthenticationManager的认证逻辑链。

内容的提问来源于stack exchange,提问作者Alex_Pap

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 22:50:33