一、shiro授权基础概念
(1)基于角色的访问控制
Shiro 提供了hasRole/hasRole 用于判断用户是否拥有某个角色/某些权限:
subject().hasRole("role1");//判断拥有角色:role1
subject().hasAllRoles(Arrays.asList("role1", "role2"));
subject().hasRoles(Arrays.asList("role1", "role2", "role3"));
Shiro 提供的checkRole/checkRoles 和hasRole/hasAllRoles 不同的地方是它在判断为假的情况下会抛出UnauthorizedException异常。
记住一点,shiro不提供角色和权限的维护,如果程序其他地方要用到权限或角色信息,或者如果需要在应用中判断用户是否有相应角色,用户是否有权限,就需要在相应的Realm中返回角色、权限信息,所有的信息都可以通过SecurityUtils.getSubject()来获取,包括session,host
(2)基于权限的访问控制
subject().isPermitted("user:create");//判断拥有权限:user:create
subject().isPermittedAll("user:update", "user:delete");//判断拥有权限:user:update and user:delete
subject().isPermitted("user:view");//判断没有权限:user:view
Shiro 提供了isPermitted 和isPermittedAll 用于判断用户是否拥有某个权限或所有权限,但失败的话,会抛出UnauthorizedException异常。
(3)权限的格式
“资源标识符:操作:对象实例ID” 即对哪个资源的哪个实例可以进行什么操作。其默认支持通配符权限字符串,“:”表示资源/操作/实例的分割;“,”表示操作的分割;“*”表示任意资源/操作/实例。
“资源标识符:操作:对象实例ID” 即对哪个资源的哪个实例可以进行什么操作。其默认支持通配符权限字符串,“:”表示资源/操作/实例的分割;“,”表示操作的分割;“*”表示任意资源/操作/实例。
实际上还是不需要到实例级别的控制,如果到实例级别,数据量太大,会下降其性能。在本篇文章的鉴权实例中,权限的格式为“资源标识符:操作”
举个例子:
eg1: system:user:update,system:user:insert
这个表示用户拥有资源“system:user”的“update”和“insert”权限。
鉴权判断:
subject().checkPermissions("system:user:update", "system:user:insert");
subject().checkPermissions("system:user:update,insert"); //作用同上
注意:通过“system:user:update,insert”验证"system:user:update, system:user:insert"是没问题的,但是反过来是规则不成立。
eg2: 用户拥有资源“system:user”的“create”、“update”、“delete”和“view”所有权限。
system:user:*
subject().checkPermissions("system:user:*");
</