@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Resource
UserService userService;
/**
* @Classname UserDetailsServiceImpl
* @Description 自定义一个UserDetailsService接口实现类进行用户认证信息封装
* @Date 2021-12-11
* @Created by samLi
*/
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//1.查找用户
User user = userService.findUserByUsername(username);
//2.查找用户对应的权限
List<Authority> authorities = userService.getUserAuthority(username);
//3.封装到SimpleGrantedAuthority中
//流式语法
List<SimpleGrantedAuthority> simpleGrantedAuthorities = authorities.stream().map(authority -> new
SimpleGrantedAuthority(authority.getAuthority())).collect(Collectors.toList());
if (user != null) {
UserDetails userDetails = new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), simpleGrantedAuthorities);
return userDetails;
} else {
// 如果查询的用户不存在(用户名不存在),必须抛出此异常
throw new UsernameNotFoundException("当前用户不存在!");
}
}
}