写在业务层 @Component @Slf4j public class UserDetailsServiceImpl implements UserDetailsService { @Resource private RestTemplate restTemplate; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { //1.调用根据用户名获得用户对象的Rest接口 String url="http://sys-service/v1/auth/user?username={1}"; //getForObject方法第三个参数开始是参入url{}中占位符用的 User user=restTemplate.getForObject(url,User.class,username); log.debug("查询出用户:{}",user); //2.判断用户不为空 if(user==null){ throw new UsernameNotFoundException("用户名密码错误"); } //3.调用根据用户id获得用户权限的Rest接口 url="http://sys-service/v1/auth/permissions?userId={1}"; //凡是Rest接口返回List格式的,调用时使用对应泛型的数组类型接收 //原因是传递过程中数据是json格式,json格式是js代码,js代码没有List类型 Permission[] permissions=restTemplate.getForObject( url,Permission[].class,user.getId()); //4.调用根据用户id获得用户角色的Rest接口 url="http://sys-service/v1/auth/roles?userId={1}"; Role[] roles=restTemplate.getForObject( url,Role[].class,user.getId()); //5.将权限和角色赋值到auth数组中 if(permissions==null || roles==null){ throw new UsernameNotFoundException("当前用户权限不足"); } //声明保存所有权限和角色的数据 String[] auth=new String[permissions.length+roles.length]; int i=0; for(Permission p :permissions){ auth[i++]=p.getName(); } for(Role r:roles ){ auth[i++]=r.getName(); } //6.构造UserDetails对象 UserDetails u= org.springframework.security.core.userdetails .User.builder() .username(user.getUsername()) .password(user.getPassword()) .authorities(auth) .accountLocked(user.getLocked()==1) .disabled(user.getEnabled()==0) .build(); //不要忘了返回u!!!! return u; } }
ribbin 从CONTROLLER的REST接口接收数据
最新推荐文章于 2024-02-02 15:29:09 发布