shiro 基于权限访问
直接进入主题:
创建一个简单的maven项目:
首先导入依赖包
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.zs.shiro</groupId>
<artifactId>Shiro02</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Shiro02</name>
<description>Shiro02</description>
<dependencies>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.2.4</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.12</version>
</dependency>
</dependencies>
</project>
编写基本的shiro配置工厂,在/Shiro01/src/main/resources下,文件名为 shiro.ini
#用户
[users]
#用户zs的密码是123,此用户具有role1和role2两个角色
zs=123,role1,role2
wang=123,role2
#权限
[roles]
role1=user:select
role2=user:add,user:update,user:delete
现在进入正题:编写一个简单的列子,在/Shiro02/src/main/java下,创建/Shiro02/src/main/java/com/zs/shiro/Shiro02Test.java。
package com.zs.shiro;
import java.util.Arrays;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
public class Shiro02Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Factory<SecurityManager> factory =new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManages=factory.getInstance();
SecurityUtils.setSecurityManager(securityManages);
Subject userAndRole=SecurityUtils.getSubject();
UsernamePasswordToken userToken=new UsernamePasswordToken("zs","123");
userAndRole.login(userToken);
System.out.println("登录成功:"+userAndRole.getPrincipal());
System.out.println(userAndRole.hasRole("role1")?"有role1角色":"没有role1角色");
//获取该用户的所有角色
boolean []results=userAndRole.hasRoles(Arrays.asList("role1","role2","role3"));
System.out.println(results[0]?"有role1角色":"没有role1角色");
System.out.println(results[1]?"有role2角色":"没有role2角色");
System.out.println(results[2]?"有role3角色":"没有role3角色");
//判断权限
System.out.println(userAndRole.isPermitted("user:add")?"具有该权限":"没有该权限");
userAndRole.logout();
}
}
结果如下: