springboot+security整合1 (3)

编写了实体类还需要编写一个服务类SecurityService实现UserDetailsService接口,重写loadByUsername方法,通过这个方法根据用户名获取用户信息,代码如下:

@Component public class SecurityUserService implements UserDetailsService { @Autowired private JurisdictionMapper jurisdictionMapper; @Autowired private UserMapper userMapper; private Logger log = LoggerFactory.getLogger(this.getClass()); @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { log.info("登录用户id为:{}",username); int id = Integer.valueOf(username); User user = userMapper.getById(id); if(user==null) { //抛出错误,用户不存在 throw new UsernameNotFoundException("用户名 "+username+"不存在"); } //获取用户权限 List<GrantedAuthority> authorities = new ArrayList<>(); List<Jurisdiction> jurisdictions = jurisdictionMapper.selectByUserId(id); for(Jurisdiction item : jurisdictions) { GrantedAuthority authority = new MyGrantedAuthority(item.getMethod(),item.getUrl()); authorities.add(authority); } SecurityUser securityUser = new SecurityUser(user.getName(),user.getPassword(),authority): user.setAuthorities(authorities); return securityUser; } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpwsgs.html