Shiro笔记(三)授权

时间:2022-05-30 19:28:29

Shiro笔记(三)授权

一、授权方式

1.编程式:

 Subject subject=SecurityUtils.getSubject();
if(subject.hasRole("root")){
//有权限
} else {
//无权限
}

2.注解式:

 @RequiresRoles("admin")
public void hello(){
//有权限才执行
}

3.JSP标签:

 <shiro:hasRole name="root">

 <!--有权限-->
</shiro:hasRole>

二、授权

1.基于角色的访问控制

规则:用户名=密码,角色1,角色2......

shiro-role.ini文件:

 [users]
tang=123,role1,role2
wang=321,role1

核心代码:

 /**
* @author Tang Jiujia
* @since 2017-10-16
*/
public class RoleTest extends BaseTest{ @Test
public void testHasRole(){
login("src/main/shiro-role.ini","tang","123");
Subject subject= SecurityUtils.getSubject();
Assert.assertTrue(subject.hasRole("role1"));
Assert.assertTrue(subject.hasAllRoles(Arrays.asList("role1","role2")));
boolean[] hasRoles = subject.hasRoles(Arrays.asList("role1", "role2", "role3")); for (int i=0;i<3;i++){
if (hasRoles[i]==true){
System.out.println("We have role"+(i+1));
}else {
System.out.println("We don't have role"+(i+1));
}
}
}
}
 //checkRole与前面的hasRole不同的地方在于判断为假时会抛UnauthorizedException
@Test(expected = UnauthorizedException.class)
public void testCheckRole(){
login("src/main/shiro-role.ini","tang","123");
Subject subject= SecurityUtils.getSubject();
subject.checkRole("role1");
subject.checkRoles("role1","role5");
}

2.基于资源的访问控制

规则:用户名=密码,角色1,角色2            角色=权限1,权限2

 [users]
tang=123,role1,role2
wang=321,role2
[roles]
role1=root:create,root:add,root:update
role2=root:delete,root:update

核心代码:

 /**
* @author Tang Jiujia
* @since 2017-10-16
*/
public class PermissionTest extends BaseTest{ @Test
public void testIsPermission(){
login("src/main/shiro-permission.ini","tang","123456");
Subject subject = SecurityUtils.getSubject();
if (subject.isPermitted("root:add1")) {
System.out.println("have add");
} else {
System.out.println("do not have add");
}
if (subject.isPermitted("root:update")) System.out.println("Have update permission");
} @Test
public void testCheckPermission(){
login("src/main/shiro-permission.ini","tang","123456");
Subject subject = SecurityUtils.getSubject();
subject.checkPermission("root:add");
}
}