Spring Security Custom Authentication - AuthenticationProvider vs UserDetailsService
据我所知,当您想要在Spring Security中进行自定义身份验证时,您可以实现自定义或自定义 。AuthenticationProvider
UserDetailsService
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
//.authenticationProvider(authProvider) // option 1
.userDetailsService(userDetailsService); // option 2
}
在身份验证提供程序中,您可以检查用户名和密码,并在其中返回自定义对象。Authentication
public Authentication authenticate(Authentication authentication){
if (checkUsernameAndPassword(authentication)) {
CustomUserDetails userDetails = new CustomUserDetails();
//add whatever you want to the custom user details object
return new UsernamePasswordAuthenticationToken(userDetails, password, grantedAuths);
} else {
throw new BadCredentialsException("Unable to auth against third party systems");
}
}
在 中,您只能获得用户名,当您返回自定义 UserDeatails 时,框架将对密码执行检查。UserDetailsService
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
CustomUserDetails user = new CustomUserDetails();
//add whatever you want to the custom user details object
return user;
}
看起来两者都可以产生类似的结果。那么问题来了,它们之间有什么区别呢?何时使用一个与另一个?