1、新建 java Project 。导入相关jar包如下lib中
2、新建2个配置文件:log4j.properties 和 shiro-permission.ini
1) log4j.properties中添加内容如下:log4j.rootLogger=debug,stdoutlog4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n2) shiro-permission.ini中添加如下内容:#对用户信息进行配置[users]#用户名和密码,此用户具有role1和role2两个角色zhangsan=123,role1,role2wang=123,role2#权限[roles]#角色role1对资源user拥有create、update权限role1=user:create,user:update#角色role2对资源user拥有create、delete权限role2=user:create,user:delete#角色role3对资源user拥有create权限role3=user:create
3、新建测试程序:
public class AuthorizationTest {//角色授权、资源授权测试@Testpublic void testAuthorization(){//创建SecurityManagerFactory<SecurityManager> factory=new IniSecurityManagerFactory("classpath:shiro-permission.ini");//创建SecurityManagerSecurityManager securityManager=factory.getInstance();//将SecurityManager设置到系统运行环境当中,和spring整合后也要将SecurityManager配置到spring容器中,一般是单利管理SecurityUtils.setSecurityManager(securityManager);//创建subjectSubject subject=SecurityUtils.getSubject();//创建token令牌UsernamePasswordToken token=new UsernamePasswordToken("zhangsan", "123");try {subject.login(token);} catch (Exception e) {// TODO: handle exception}System.out.println("认证状态:"+subject.isAuthenticated());//***********认证通过后进行授权*************************//============基于角色的授权============================//hasRole传入角色标识boolean ishasRole=subject.hasRole("role1");System.out.println("单个角色判断:"+ishasRole);//hasAllRoles是否拥有多个角色boolean hasAllRoles=subject.hasAllRoles(Arrays.asList("role1","role2"));System.out.println("多个角色判断:"+hasAllRoles);//使用check方法进行授权,如果授权不通过会抛出异常//subject.checkRole("role12");//=================基于资源的授权============================//isPermitted传入权限标识符boolean isPermitted = subject.isPermitted("user:create:1");System.out.println("单个权限判断:"+isPermitted);boolean isPermittedAll=subject.isPermittedAll("user:create","user:update");System.out.println("多个权限判断:"+isPermittedAll);//使用check方法进行授权,如果授权不通过会抛出异常subject.checkPermission("items:create:1");}}