概述
我们可以通过继承AuthenticationProvider
或者其实现来完成自定义身份认证处理器
通常身份验证处理器主要是完成对用户名密码的验证和判断用户时候可用等
实现案例
以下是实现方法
1. 继承于AuthenticationProvider
new AuthenticationProvider() {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
// 进行身份认证的方法
if ("admin".equals(authentication.getPrincipal()) && "123456".equals(authentication.getCredentials())) {
List<GrantedAuthority> grantedAuthorities = Arrays.asList(new SimpleGrantedAuthority("admin"));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getAuthorities(), grantedAuthorities);
token.setDetails(authentication.getDetails());
return token;
}else{
throw new BadCredentialsException("账号密码错误");
}
}
@Override
public boolean supports(Class<?> aClass) {
// 支持何种类型的身份认证
return UsernamePasswordAuthenticationToken.class.isAssignableFrom(aClass);
}
}
2. 在AuthenticationManager
中使用这个Provider
处理器即可
// 提交给实现 ProviderManager 使用
new ProviderManager(providers);