Spring Security - 从数据库中检索用户信息(二)

时间 2021/5/28 16:21:08 加载中...

修改为从数据库访问

这里将之前的直接返回一个用户,修改为从数据库访问并返回

  1. public class CustomUserService implements UserDetailsService {
  2. @Override
  3. public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
  4. try {
  5. com.example.demo.model.userInfo.User userDb = userService.getUserByUserCode(userName);
  6. if (userDb == null)
  7. throw new UsernameNotFoundException("用户名或密码不正确");
  8. String encodePassword = userDb.getPassword();
  9. //String encodePassword = new BCryptPasswordEncoder().encode(password);
  10. List<GrantedAuthority> authorities = getAuthorities(userName);
  11. MyUser user = new MyUser(userName, encodePassword, authorities);
  12. user.setRealName(userDb.getUserName());
  13. return user;
  14. } catch (Exception e) {
  15. throw new UsernameNotFoundException("用户名或密码不正确");
  16. }
  17. }
  18. private List<GrantedAuthority> getAuthorities(String userName) throws Exception {
  19. List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
  20. //authorities.add(new SimpleGrantedAuthority("role_user"));
  21. //data from database
  22. List<Role> roles = roleService.getRolesByUserCode(userName);
  23. if (roles != null) {
  24. roles.forEach(r -> authorities.add(new SimpleGrantedAuthority(r.getRoleName())));
  25. }
  26. return authorities;
  27. }
  28. }
  29. }

userService 和 roleService 自己自由选择数据库访问技术实现即可。

自定义 User 类

另外,这里扩展了 User 类,新增了 realName 昵称

  1. public class MyUser extends User {
  2. private String realName;
  3. public MyUser(String username, String password, Collection<? extends GrantedAuthority> authorities) {
  4. super(username, password, authorities);
  5. }
  6. public String getRealName() {
  7. return realName;
  8. }
  9. public void setRealName(String realName) {
  10. this.realName = realName;
  11. }
  12. public MyUserDTO toMyUserDTO() {
  13. return new MyUserDTO(this.realName, this.getUsername());
  14. }
  15. public class MyUserDTO {
  16. private String realName;
  17. private String userName;
  18. public String getRealName() {
  19. return realName;
  20. }
  21. public void setRealName(String realName) {
  22. this.realName = realName;
  23. }
  24. public String getUserName() {
  25. return userName;
  26. }
  27. public void setUserName(String userName) {
  28. this.userName = userName;
  29. }
  30. public MyUserDTO(String realName, String userName) {
  31. this.realName = realName;
  32. this.userName = userName;
  33. }
  34. }
  35. }

测试

修改数据库的用户信息,验证是否能正常登录

扫码分享
版权说明
作者:SQBER
文章来源:http://www.sqber.com/articles/spring-security-retrive-user-from-db-2.html
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。