Shiro支持三种方式实现授权过程:
- 编码实现
- 注解实现
- JSP Taglig实现
1、基于编码的授权实现
基于传统角色授权实现
当需要验证用户是否拥有某个角色时,可以调用Subject 实例的hasRole()方法验证
Subject currentUser = SecurityUtils.getSubject();
if (currentUser.hasRole("administrator")) {
//show the admin button
} else {
//don't show the button? Grey it out?
}
Subject方法 描述
1:hasRole(String roleName)
当用户拥有指定角色时,返回true
2:hasRoles(List<String> roleNames)
按照列表顺序返回相应的一个boolean值数组
3:hasAllRoles(Collection<String> roleNames)
如果用户拥有所有指定角色时,返回true
断言支持
Shiro还支持以断言的方式进行授权验证。断言成功,不返回任何值,程序继续执行;断言失败时,将抛出异常信息。使用断言,可以使我们的代码更加简洁。
Subject currentUser = SecurityUtils.getSubject();
currentUser.checkRole("bankTeller");
openBankAccount();
断言的相关方法: Subject方法 描述
checkRole(String roleName)
断言用户是否拥有指定角色
checkRoles(Collection<String> roleNames)
断言用户是否拥有所有指定角色
checkRoles(String... roleNames)
对上一方法的方法重载
基于权限角色授权实现
相比传统角色模式,基于权限的角色模式耦合性要更低些,它不会因角色的改变而对源代码进行修改,因此,基于权限的角色模式是更好的访问控制方式。
它的代码实现有以下几种实现方式:
1、基于权限对象的实现
创建org.apache.shiro.authz.Permission的实例,将该实例对象作为参数传递给Subject.isPermitted()进行验证。
Permission printPermission = new PrinterPermission("laserjet4400n", "print");
Subject currentUser = SecurityUtils.getSubject();
if (currentUser.isPermitted(printPermission)) {
//show the Print button
} else {
//don't show the button? Grey it out?
}
相关方法如下: Subject方法 描述
isPermitted(Permission p)
Subject拥有制定权限时,返回true
isPermitted(List<Permission> perms)
返回对应权限的boolean数组
isPermittedAll(Collection<Permission> perms)
Subject拥有所有制定权限时,返回true
2、 基于字符串的实现
相比笨重的基于对象的实现方式,基于字符串的实现便显得更加简洁。
Subject currentUser = SecurityUtils.getSubject();
if (currentUser.isPermitted("printer:print:laserjet4400n")) {
//show the Print button
} else {
//don't show the button? Grey it out?
}
使用冒号分隔的权限表达式是org.apache.shiro.authz.permission.WildcardPermission
默认支持的实现方式。
这里分别代表了 资源类型:操作:资源ID
类似基于对象的实现相关方法,基于字符串的实现相关方法:
isPermitted(String perm)
isPermitted(String... perms)
isPermittedAll(String... perms)
基于权限对象的断言实现
Subject currentUser = SecurityUtils.getSubject();
Permission p = new AccountPermission("open");
currentUser.checkPermission(p);
openBankAccount();
基于字符串的断言实现
Subject currentUser = SecurityUtils.getSubject();
currentUser.checkPermission("account:open");
openBankAccount();
断言实现的相关方法 Subject方法 说明
checkPermission(Permission p)
断言用户是否拥有制定权限
checkPermission(String perm)
断言用户是否拥有制定权限
checkPermissions(Collection<Permission> perms)
断言用户是否拥有所有指定权限
checkPermissions(String... perms)
断言用户是否拥有所有指定权限
转自博客:https://blog.csdn.net/xiaoliuliu2050/article/details/54911480