DaoAuthenticationProvider
DaoAuthenticationProvider 是一个 AuthenticationProvider 实现,它使用 UserDetailsService 和 PasswordEncoder 来验证用户名和密码。
本节将探讨 DaoAuthenticationProvider 在 Spring Security 中的工作原理。以下图表从读取用户名和密码部分的图表中解释了 AuthenticationManager 的工作原理。

图 1. DaoAuthenticationProvider 用法
1 从读取用户名和密码部分的认证 Filter 会将一个 UsernamePasswordAuthenticationToken 传递给 AuthenticationManager,而 AuthenticationManager 是由 ProviderManager 实现的。
2 ProviderManager 被配置为使用类型为 DaoAuthenticationProvider 的 AuthenticationProvider。
3 DaoAuthenticationProvider 从 UserDetailsService 查找 UserDetails。
4 DaoAuthenticationProvider 使用 PasswordEncoder 来验证上一步返回的 UserDetails 中的密码。
5 当身份验证成功时,返回的Authentication 类型为 UsernamePasswordAuthenticationToken,并且其 principal 是由配置的 UserDetailsService 返回的 UserDetails。最终,返回的 UsernamePasswordAuthenticationToken 由身份验证 Filter 设置在 SecurityContextHolder 上。