进入到ProviderManager
这个类当中的authenticate方法。
// member variable
private List<AuthenticationProvider> providers; // provider集合
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
Class<? extends Authentication> toTest = authentication.getClass();
Authentication result = null;
int size = this.providers.size();
Iterator var9 = this.getProviders().iterator();
// 遍历 Provider
while(var9.hasNext()) {
AuthenticationProvider provider = (AuthenticationProvider)var9.next();
// 找到和 authentication 匹配的 provider
if (provider.supports(toTest)) {
try {
// 用匹配的provider去认证
result = provider.authenticate(authentication);
if (result != null) {
this.copyDetails(authentication, result);
break;
}
}
}
}
}
包装Authentication(基本就是照抄UsernamePasswordAuthenticationToken)
/**
* 用于邮箱登录
*/
public class MailAuthenticationToken extends AbstractAuthenticationToken {
private final Object principal;
private Object credentials;
public MailAuthenticationToken(Object principal, Object credentials) {
super(null);
this.principal = principal;
this.credentials = credentials;
this.setAuthenticated(false);
}
public MailAuthenticationToken(Object principal, Object credentials, Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.principal = principal;
this.credentials = credentials;
super.setAuthenticated(true);
}
}
模仿AbstractUserDetailsAuthenticationProvider
,DaoAuthenticationProvider
,自定义一个AuthenticationProvider ,实现认证逻辑
有些防止攻击,校验参数是否为null,get/set方法,更新密码的东西都删去了。
/**
* 邮箱登录校验逻辑
*/
@Slf4j
@Component
public class MailProvider implements AuthenticationProvider {
@Autowired
private MailUserDetailsServiceImpl mailUserDetailsService;
@Autowired
private RedisTemplate redisTemplate;
// private final Log logger = LogFactory.getLog(this.getClass());
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
UserDetails user;
// 用户名校验(是否可以查得到)
try {
user = mailUserDetailsService.loadUserByUsername(username);
} catch (UsernameNotFoundException var6) {
log.debug("Failed to find user '" + username + "'");
throw new BadCredentialsException("MailAuthenticationProvider.badCredentials");
}
// 密码校验
if(authentication.getCredentials() == null){
log.debug("Failelogd to authenticate since no credentials provided");
throw new BadCredentialsException("MailAuthenticationProvider.badCredentials");
}else{
String presentedPassword = authentication.getCredentials().toString();
String mail_code = (String)redisTemplate.opsForValue().get(username);
// 验证码过期
if(mail_code == null){
throw new BusinessException(401,"验证码已过期");
}
// 验证码错误
if (presentedPassword != mail_code) {
log.debug("Failed to authenticate since password does not match stored value");
throw new BadCredentialsException("MailAuthenticationProvider.badCredentials");
}
}
MailAuthenticationToken token = new MailAuthenticationToken(user,authentication.getCredentials(),user.getAuthorities());
return token;
}
@Override
public boolean supports(Class<?> authenticaton) {
return MailAuthenticationToken.class.isAssignableFrom(authenticaton);
}
}
UserDetailsService实现类
@Component
public class MailUserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserDao userDao;
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
User user = userDao.findByEmail(email);
if(user == null){
throw new UsernameNotFoundException(email);
}
return new UserDetailsImpl(user); // 包装返回
}
}
在SpringSecurity配置对应的AuthenticationManager
@Autowired
private AuthenticationProvider daoProvider;
@Autowired
private AuthenticationProvider mailProvider;
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
AuthenticationManager auth = new ProviderManager(Arrays.asList(mailProvider,daoProvider));
return auth;
}
Service层登录业务代码
public Result loginCheck(LoginData loginData){
Authentication authentication = null;
if(loginData.getLoginType() == 0){
authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginData.getUsername(), loginData.getPassword())
);
}
if(loginData.getLoginType() == 1){
authentication = authenticationManager.authenticate(
new MailAuthenticationToken(loginData.getUsername(), loginData.getPassword())
);
}
// 从loadUserByUsername方法中查到该用户的信息, 封装到UserDetails,
// 之后又塞到了UsernamePasswordAuthenticationToken的Principal属性中
UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
String username = userDetails.getUsername();
String token = JwtUtils.createToken(username);
Map<String,String> map = new HashMap<>();
map.put("token",token);
redisTemplate.opsForValue().set("token::"+token,userDetails, Duration.ofHours(1));
userDao.updateLoginStatus(LocalDateTime.now(),1,userDetails.getUser().getId());
return new Result(200,"ok",map);
}
UserDetailsPasswordService是用来更新密码的接口
AuthenticationManager,AuthenticationProvider,UserDetailsService的关系
SpringSecurity多种登录方式
配置多个AuthenticationProvider