【发布时间】:2015-10-16 07:46:20
【问题描述】:
据我所知,当您希望在 Spring Security 中进行自定义身份验证时,您可以实现自定义 AuthenticationProvider 或自定义 UserDetailsService。
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
//.authenticationProvider(authProvider) // option 1
.userDetailsService(userDetailsService); // option 2
}
在 AuthenticationProvider 中,您可以检查用户名和密码并返回 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");
}
}
在UserDetailsService 中,您只获得用户名,当您返回自定义 UserDeatails 时,框架会检查密码。
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
CustomUserDetails user = new CustomUserDetails();
//add whatever you want to the custom user details object
return user;
}
看起来两者都可以产生相似的结果。所以问题是有什么区别?何时使用一个与另一个?
【问题讨论】:
-
感谢您提出这个问题。仅仅因为你问它,它就为我阐明了架构。
-
@AdamEdison-MusicEducator 很高兴它有帮助。
标签: java spring spring-mvc spring-security