DaoAuthenticationProvider
DaoAuthenticationProvider 是一个 AuthenticationProvider 实现,它使用 UserDetailsService 和 PasswordEncoder 来验证用户名和密码。
本节将探讨 DaoAuthenticationProvider 在 Spring Security 中的工作原理。下图通过读取用户名与密码章节中的图示,解释了AuthenticationManager 的工作机制。

图 1. DaoAuthenticationProvider 使用
1 来自读取用户名和密码部分的认证Filter会向AuthenticationManager传递一个UsernamePasswordAuthenticationToken,该管理器由ProviderManager实现。
2 ProviderManager 被配置为使用类型为 DaoAuthenticationProvider 的 AuthenticationProvider。
3 DaoAuthenticationProvider 从 UserDetailsService 中查找 UserDetails。
4 DaoAuthenticationProvider 使用 PasswordEncoder 来验证上一步返回的 UserDetails 中的密码。
5 当认证成功时,返回的 Authentication 类型为 UsernamePasswordAuthenticationToken,其主体(principal)是由配置的 UserDetailsService 返回的 UserDetails,并且包含一组权限,其中至少包含 FACTOR_PASSWORD。最终,返回的 UsernamePasswordAuthenticationToken 由认证 Filter 设置在 SecurityContextHolder 上。