版权声明:程序猴jwang版权所有 https://blog.csdn.net/qq_21046965/article/details/90110243
前言
本章讲解Shiro授权的相关知识
方法
1.概念
Authorization:授权,也就是授予用户访问某些资源的权限。
前提在于需要用户通过登录验证才可以进行授权。
权限(permit):表示某些功能,如按钮的显示,菜单的访问,数据的CRUD
角色(role): 权限的集合,比如管理员角色,其拥有访问系统全部菜单的权限
2.Shiro中用户的授权流程
3.实现步骤
我们仍然使用之前做登陆验证时候的代码。
1)编写shiro.ini文件
[main]
[users]
zhangsan = 1234,role1
lisi = 5678
[roles]
role1 = permit1,permit2
注意:上面的配置文件中,users配置的为用户名 = 密码,角色1,角色2...
roles配置为角色 = 权限1,权限2...
2)编码实现
package cn.edu.ccut.test;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.apache.shiro.mgt.SecurityManager;
/**
* @Auther:jwang
* @Date:2019/5/8
* @Description:cn.edu.ccut.test
* @Version 1.0
**/
public class Authentication {
public static void main(String [] args){
//创建SecurityManager工厂
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
//通过SecurityManager工厂获取SecurityManager实例
SecurityManager securityManager = factory.getInstance();
//将SecurityManager对象设置到运行环境中
SecurityUtils.setSecurityManager(securityManager);
//通过SecurityUtils获取主体Subject
Subject currentUser = SecurityUtils.getSubject();
//设置用户名和密码
String username = "zhangsan";
String password = "1234";
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
//进行用户身份验证
try {
currentUser.login(token);
//如果用户认证成功
if (currentUser.isAuthenticated()) {
System.out.println("用户["+username+","+password+"]登录成功!");
//判断用户是否拥有权限role1
String role = "role1";
boolean isRole1 = currentUser.hasRole(role);
System.out.println("用户["+username+","+password+"]"+(isRole1?"拥有":"未拥有")+"权限"+role);
if(isRole1){
//this code here
}
}
}catch (AuthenticationException e){
System.out.println("用户["+username+","+password+"]登录失败!");
}
}
}
执行结果如下:
注意:这里我们使用了hasRole方法来判断用户是否拥有某角色。
在shiro中,有以下方法用来判断用户是否拥有相关的角色和权限:
角色:
boolean hasRole(String roleIdentifier) | 判断用户是否拥有某角色,true表示拥有,false则没有 |
boolean[] hasRoles(List<String> roleIdentifiers); | 判断用户是否拥有某些角色,返回布尔数组 |
boolean hasAllRoles(Collection<String> roleIdentifiers); | 判断用户是否拥有某些角色,全部满足返回true,反之false |
void checkRole(String roleIdentifier) throws AuthorizationException | 判断用户是否拥有某角色,没有抛出异常 |
void checkRoles(Collection<String> roleIdentifiers) throws AuthorizationException; | 判断用户是否拥有全部角色,没有抛出异常 |
void checkRoles(String... roleIdentifiers) throws AuthorizationException; | 判断用户是否拥有全部角色,没有抛出异常 |
权限:
boolean isPermitted(String permission); | 判断用户是否拥有某权限,true表示拥有,false则没有 |
boolean[] isPermitted(String... permissions); | 判断用户是否拥有某些权限,返回布尔数组 |
boolean isPermittedAll(String... permissions); | 判断用户是否拥有全部权限,有返回true,反之false |
void checkPermission(String permission) throws AuthorizationException; | 判断用户是否拥有某权限,没有抛出异常 |
void checkPermissions(String... permissions) throws AuthorizationException; | 判断用户是否拥有全部权限,没有抛出异常 |