当你想要在 Spring Security 中进行自定义身份验证时,您可以实现自定义AuthenticationProvider
或自定义UserDetailsService
.
AuthenticationProvider:
在 AuthenticationProvider 中,可以检查用户名和密码,并在其中返回Authentication
自定义对象。
UserDetailsService:
在UserDetailsService
您只获得用户名时,当您返回自定义 UserDeatails 时,框架会检查密码
问题:什么情况下使用AuthenticationProvider、
那种情况下又使用
UserDetailsService
呢?
当您使用不同的身份验证系统,并且您自己的数据库/数据模型中未提供密码时,您必须使用 AuthenticationProvider。例如,我在一个项目中工作,客户有一个集中式身份验证系统(CAS),所以我的系统不知道密码,我必须实现 AuthenticationProvider 并将给定的密码发送给 CAS,然后获取它的返回结果在进行下一步。
但是在另一个系统中,我将密码存储在我的数据库中,所以我所要做的就是实现 UserDetailsService 并检查用户是否存在于我的数据库中,剩下的事情就交给 spring-security 了。