MyAuthenticationProvider.java 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package com.bizmatics.service.config.security;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.security.authentication.AuthenticationProvider;
  4. import org.springframework.security.authentication.BadCredentialsException;
  5. import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
  6. import org.springframework.security.core.Authentication;
  7. import org.springframework.security.core.AuthenticationException;
  8. import org.springframework.security.core.GrantedAuthority;
  9. import org.springframework.security.core.userdetails.UserDetails;
  10. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  11. import org.springframework.stereotype.Component;
  12. import java.util.Collection;
  13. /**
  14. * 实现自己的AuthenticationProvider类,用来自定义用户校验机制
  15. * @author zhoukebo
  16. * @date 2018/9/5
  17. */
  18. @Component
  19. public class MyAuthenticationProvider implements AuthenticationProvider {
  20. @Autowired
  21. private CustomerDetailServiceImpl customerDetailServiceImpl;
  22. @Override
  23. public Authentication authenticate(Authentication authentication) throws AuthenticationException {
  24. // 获取表单输入中返回的用户名;
  25. String userName = (String) authentication.getPrincipal();
  26. // 获取表单中输入的密码;
  27. String password = (String) authentication.getCredentials();
  28. // 这里调用我们的自己写的获取用户的方法;
  29. UserDetails userInfo = customerDetailServiceImpl.loadUserByUsername(userName);
  30. if (userInfo == null) {
  31. throw new BadCredentialsException("用户名不存在");
  32. }
  33. // 这里我们还要判断密码是否正确,这里我们的密码使用BCryptPasswordEncoder进行加密的
  34. if (!new BCryptPasswordEncoder().matches(password, userInfo.getPassword())) {
  35. throw new BadCredentialsException("密码不正确");
  36. }
  37. // 这里还可以加一些其他信息的判断,比如用户账号已停用等判断。
  38. Collection<? extends GrantedAuthority> authorities = userInfo.getAuthorities();
  39. // 构建返回的用户登录成功的token
  40. return new UsernamePasswordAuthenticationToken(userInfo, password, authorities);
  41. }
  42. @Override
  43. public boolean supports(Class<?> authentication) {
  44. // 这里直接改成retrun true;表示是支持这个执行
  45. return true;
  46. }
  47. }