【问题标题】:difference between overriding configure(AuthentiationManageraBuilder) method vs just creating a DaoAuthenticationProvider覆盖 configure(AuthentiationManageraBuilder) 方法与仅创建 DaoAuthenticationProvider 之间的区别
【发布时间】:2020-07-10 04:10:25
【问题描述】:
我正在尝试使用 JPA 的 Spring Security 身份验证。我遇到了两个 youtube 频道(Java Brains)和(Telusko)。 Java Brains 的家伙已经覆盖了 WebSecurityConfigurer 的 configure(AuthenticationManagerBuilder Auth) 方法,而 Telusko 的家伙使用 bean 来设置 DaoAuthenticationProvider 来配置 userDetailService。我知道 authenticationManager 调用 authenticationProvider ,后者又调用 userDetailService 来加载用户。如果我错了,请纠正。有人可以解释一下这两种方法之间的区别是什么。提前致谢。
【问题讨论】:
标签:
spring-mvc
spring-security
spring-data-jpa
【解决方案1】:
区别在于一种身份验证方式(DaoAuthenticationProvider)与开放更多选择(AuthenticationManagerBuilder)。
通过配置 DaoAuthenticationProvider,意味着您选择“Dao”/“userDetailService”来验证您的用户。
Spring Security 使用 Authentication Manager 进行身份验证,ProviderManager 是默认的身份验证管理器,它通过 AuthenticationProviders 列表迭代一个 Authentication 请求。而 DaoAuthenticationProvider 就是其中之一。
通过使用方法配置身份验证管理器:configure(AuthenticationManagerBuilder Auth)
您有更多的灵活性,您可以配置身份验证管理器以使用您自定义的身份验证提供程序。 (而你的 CustomAuthenticationProvider 实现了 AuthenticationProvider 接口)
@Autowired
private CustomAuthenticationProvider customAuthProvider;
@Override
public void configure(AuthenticationManagerBuilder auth) {
auth.authenticationProvider(customAuthProvider);
}
您还可以通过简单地提供 userdetailservice 来配置 DaoAuthenticationProvider,因为 AuthenticationManagerBuilder 会连接它。
@Autowired
private CustomUserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
话虽如此,使用 AuthenticationManagerBuilder 更为常见,因为它可用于配置不同类型的身份验证提供程序。