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


修改为从数据库访问
这里将之前的直接返回一个用户,修改为从数据库访问并返回
public class CustomUserService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
try {
com.example.demo.model.userInfo.User userDb = userService.getUserByUserCode(userName);
if (userDb == null)
throw new UsernameNotFoundException("用户名或密码不正确");
String encodePassword = userDb.getPassword();
//String encodePassword = new BCryptPasswordEncoder().encode(password);
List<GrantedAuthority> authorities = getAuthorities(userName);
MyUser user = new MyUser(userName, encodePassword, authorities);
user.setRealName(userDb.getUserName());
return user;
} catch (Exception e) {
throw new UsernameNotFoundException("用户名或密码不正确");
}
}
private List<GrantedAuthority> getAuthorities(String userName) throws Exception {
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
//authorities.add(new SimpleGrantedAuthority("role_user"));
//data from database
List<Role> roles = roleService.getRolesByUserCode(userName);
if (roles != null) {
roles.forEach(r -> authorities.add(new SimpleGrantedAuthority(r.getRoleName())));
}
return authorities;
}
}
}
userService 和 roleService 自己自由选择数据库访问技术实现即可。
自定义 User 类
另外,这里扩展了 User 类,新增了 realName 昵称
public class MyUser extends User {
private String realName;
public MyUser(String username, String password, Collection<? extends GrantedAuthority> authorities) {
super(username, password, authorities);
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public MyUserDTO toMyUserDTO() {
return new MyUserDTO(this.realName, this.getUsername());
}
public class MyUserDTO {
private String realName;
private String userName;
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public MyUserDTO(String realName, String userName) {
this.realName = realName;
this.userName = userName;
}
}
}
测试
修改数据库的用户信息,验证是否能正常登录
扫码分享
版权说明
作者:SQBER
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
{0}
{5}
{1}
{2}回复
{4}
*昵称:
*邮箱:
个人站点:
*想说的话: