authenticationProvider和userDetailsService之间的区别

当你想要在 Spring Security 中进行自定义身份验证时,您可以实现自定义AuthenticationProvider或自定义UserDetailsService.

   AuthenticationProvider:

   在 AuthenticationProvider 中,可以检查用户名和密码,并在其中返回Authentication自定义对象。
  UserDetailsService:

   在UserDetailsService您只获得用户名时,当您返回自定义 UserDeatails 时,框架会检查密码

问题:什么情况下使用AuthenticationProvider、那种情况下又使用UserDetailsService呢?

当您使用不同的身份验证系统,并且您自己的数据库/数据模型中未提供密码时,您必须使用 AuthenticationProvider。例如,我在一个项目中工作,客户有一个集中式身份验证系统(CAS),所以我的系统不知道密码,我必须实现 AuthenticationProvider 并将给定的密码发送给 CAS,然后获取它的返回结果在进行下一步。

但是在另一个系统中,我将密码存储在我的数据库中,所以我所要做的就是实现 UserDetailsS​​ervice 并检查用户是否存在于我的数据库中,剩下的事情就交给 spring-security 了。

给我讲讲这段代码/** * Processes an authentication form submission. Called * {@code AuthenticationProcessingFilter} prior to Spring Security 3.0. * <p> * Login forms must present two parameters to this filter: a username and password. The * default parameter names to use are contained in the static fields * {@link #SPRING_SECURITY_FORM_USERNAME_KEY} and * {@link #SPRING_SECURITY_FORM_PASSWORD_KEY}. The parameter names can also be changed by * setting the {@code usernameParameter} and {@code passwordParameter} properties. * <p> * This filter by default responds to the URL {@code /login}. * * @author Ben Alex * @author Colin Sampaleanu * @author Luke Taylor * @since 3.0 */ public class PasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter { public PasswordAuthenticationFilter(ApplicationContext applicationContext) { setRequiresAuthenticationRequestMatcher(new PathAndTypeRequestMatcher("/login", "POST", "password")); PasswordIdentityAuthenticationHandlerImpl handler; try { handler = applicationContext.getBean(PasswordIdentityAuthenticationHandlerImpl.class); } catch (BeansException e) { handler = null; } final PasswordAuthenticationProvider authenticationProvider = new PasswordAuthenticationProvider(handler); authenticationProvider.setUserDetailsService(applicationContext.getBean(UserDetailsService.class)); List<AuthenticationProvider> providers = Stream.of(authenticationProvider).collect(Collectors.toList()); ProviderManager providerManager = new ProviderManager(providers); providerManager.setAuthenticationEventPublisher(applicationContext.getBean(AuthenticationEventPublisher.class)); setAuthenticationManager(providerManager); } }
03-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值