使用ini的方式完成授权
- 编写ini 文件
在ini文件中用户、角色、权限的配置规则是:“用户名=密码,角色1,角色2...” “角色=权限1,权限2...”,首先根据用户名找角色,再根据角色找权限,角色是权限集合。
权限字符串的规则是:“资源标识符:操作:资源实例标识符”,意思是对哪个资源的哪个实例具有什么操作,“:”是资源/操作/实例的分割符,权限字符串也可以使用通配符。
例子:
用户创建权限:user:create,或user:create:
用户修改实例001的权限:user:update:001
用户实例001的所有权限:user:*:001
一般而已,我们操作只需要关注前面两节:
资源:操作 :
: : 所有资源的所有操作权限--->admin
[users]
zhangsan=222,role1,role2
lisi=888,role2
[roles]
role1=user:create,user:update
role2=user:creat,user:delete
role3=user:creat
- 测试结果
public void realmRole() {
//获取SecurityManager的实例
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:relmRole.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "222");
subject.login(token);
log.info("登录是否成功!"+subject.isAuthenticated());
log.info("验证是否有role1权限"+subject.hasRole("role1"));
log.info("验证是否有role1,role2权限"+subject.hasAllRoles(Arrays.asList("role1","role2")));
log.info("验证是否有role1,role2权限"+Arrays.toString(subject.hasRoles(Arrays.asList("role1","role2"))));
log.info("登录是否成功!"+subject.isAuthenticated());
log.info("验证是否对user资源delete操作"+subject.isPermitted("user:delete"));
}
2018-10-08 11:04:23.989 INFO 168 --- [ main] c.tuyue.SpringbootshiroApplicationTests : 登录是否成功!true
2018-10-08 11:04:23.990 INFO 168 --- [ main] c.tuyue.SpringbootshiroApplicationTests : 验证是否有role1权限true
2018-10-08 11:04:23.990 INFO 168 --- [ main] c.tuyue.SpringbootshiroApplicationTests : 验证是否有role1,role2权限true
2018-10-08 11:04:23.990 INFO 168 --- [ main] c.tuyue.SpringbootshiroApplicationTests : 验证是否有role1,role2权限[true, true]
2018-10-08 11:04:23.990 INFO 168 --- [ main] c.tuyue.SpringbootshiroApplicationTests : 登录是否成功!true
2018-10-08 11:04:23.990 INFO 168 --- [ main] c.tuyue.SpringbootshiroApplicationTests : 验证是否对user资源delete操作true