好好编程 |
您所在的位置:网站首页 › shiro如何授权 › 好好编程 |
上篇文章实现类基于Shiro的认证操作,本文来实现下授权操作。 授权 Shiro授权原理及细节内容欢迎参考如下链接 https://dpb-bobokaoya-sm.blog.csdn.net/article/details/86652418 1.获取用户对应的权限 本项目中我们的权限就只涉及到角色,没有再细粒度到菜单,感兴趣的可以自己可扩展实现下。 IUserService方法 /** * 根据用户编号获取对应的权限信息 * @param userId * @return */public List queryRoleByUserId(int userId);UserServiceImpl实现 @Overridepublic List queryRoleByUserId(int userId) { return roleMapper.queryRoleByUserId(userId);}RoleMapper接口中定义方法 List queryRoleByUserId(int userId);RoleMapper映射文件中添加sql select * from t_role t1 where t1.role_id in ( select role_id from t_user_role where user_id = #{id} )2.授权方法 修改MyRealm中授权的方法 /** * 授权的方法 */@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { // 获取认证的信息 User user = (User) principals.getPrimaryPrincipal(); // 获取登录用户对应的权限 List roles = userService.queryRoleByUserId(user.getUserId()); SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); for (Role role : roles) { // 将用户具有的角色保存到SimpleAuthorizationInfo对象中 info.addRole(role.getRoleName()); } return info;}3.SpringMVC添加配置 4.数据准备 创建一个账号分配对应的角色用来测试。 5.限制权限 // 当前登录用户需要"管理员角色才能访问"@RequiresRoles("管理员")@RequestMapping("/queryPage")public String queryPage(UserDto dto,Model model){ PageInfo pageModel = userService.queryPage(dto); model.addAttribute("pageModel", pageModel); return "user/user";}用没有"管理员"角色的访问测试 用具有访问权限的账号登录 有权的访问成功。 解决没有访问权限的跳转问题。 新建一个没有权限的跳转页面 无标题文档 $(function() { $('.error').css({ 'position' : 'absolute', 'left' : ($(window).width() - 490) / 2 }); $(window).resize(function() { $('.error').css({ 'position' : 'absolute', 'left' : ($(window).width() - 490) / 2 }); }) }); 位置: 首页 没有访问权限提示 非常遗憾,您没有权限访问该页面!看到这个提示,就自认倒霉吧! 返回首页SpringMVC中配置 redirect:/failed redirect:/login.jsp用没有权限的账号测试 权限标签在具体的业务场景中使用~ |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |