Shiro使用业务授权
业务授权中关系到几个表中的对应关系,要根据用户的角色是什么,角色的权限有哪些来给用户分配权限。
1、配置文件
在SpringShiroConfig(见认证文章)中配置advisor对象如下内容:
shiro框架底层会根据此对象的matchs返回值判断是否创建代理对象。
@Bean
public 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");
表示被这个注解描述的业务,只有有相应权限标识的角色的用户才能使用此权限。
当我用一个没有查看日志权限的用户登录时,就不能看到日志信息,更不能对其进行操作!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。