Shiro应用业务受权
业务受权中关系到几个表中的对应关系,要依据用户的角色是什么,角色的权限有哪些来给用户调配权限。
1、配置文件
在SpringShiroConfig(见认证文章)中配置advisor对象如下内容:
shiro框架底层会依据此对象的matchs返回值判断是否创立代理对象。
@Beanpublic AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) { AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor(); advisor.setSecurityManager(securityManager); return advisor;}
2、dao层
基于用户的登陆信息,获取用户的权限信息
- 依据用户id查找角色id信息;在UserRoleDao中增加一下代码:
List<Integer> findRoleIdsByUserId(Integer id);
- 映射文件
<select id="findRoleIdsByUserId" resultType="int"> select role_id from sys_user_roles where user_id=#{id}</select>
- 依据查到的角色ids查问菜单ids
List<Integer> findMenuIdsByRoleIds(Integer[] roleIds);
- 映射文件
<select id="findMenuIdsByRoleIds" resultType="int"> select menu_id from sys_role_menus where role_id in <foreach collection="roleIds" item="role_id" open="(" close=")" separator=","> #{role_id} </foreach> </select>
- 在依据查到的菜单ids查找权限标识办法
List<String> findPermissions(Integer[] menuIds);
<select id="findPermissions" resultType="string"> select premission from sys_menus where id in <foreach collection="menuIds" item="menuid" open="(" close=")" separator=","> #{menuid} </foreach></select>
3、重写ShiroUserRealm中的受权办法
/** * 受权 */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { // 1.获取用户登陆信息 SysUser user = (SysUser) principals.getPrimaryPrincipal(); Integer id = user.getId(); // 2.基于用户id查问领有的角色id List<Integer> roleIds = sysUserRolesMapper.findRoleIdsByUserId(id); // 3。基于角色id查找菜单id List<Integer> menuIds = sysRoleMenuMapper.findMenuIdsByRoleIds(roleIds); // 4。基于菜单id获取权限标识符 List<String> premissions = sysMenuMapper.findPermissions(menuIds); // 5.封装权限标识符并返回 Set<String> set = new HashSet<>(); for (String pre : premissions) { if (!StringUtils.isEmpty(pre)) { set.add(pre); } } SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(set); return info; }
4、增加注解 @RequiresPermissions(“权限标识”)
在须要进行受权拜访的业务层(Service)办法上,增加执行此办法须要的权限标识,参考代码阐明:此要注解肯定要增加到业务层办法上。
在日志查看上增加注解@RequiresPermissions("sys:log:view");
示意被这个注解形容的业务,只有有相应权限标识的角色的用户能力应用此权限。
当我用一个没有查看日志权限的用户登录时,就不能看到日志信息,更不能对其进行操作!