ACL简介:
ACL机制是zookeeper用来实现对数据节点进行权限控制的机制,类似于Unix/linux的ACL,但又不完全相同。zookeeper的权限控制是由三方面来组成的,即权限模式(Scheme),授权对象(ID),权限(Permission),用“scheme:ID:permission”来标示一个有效的ACL信息。
- 权限模式:
1.IP
通过IP地址来控制zookeeper数据节点的访问权限,例如:“IP:192.168.0.110”,即表示只有这个IP才能访问zookeeper的数据节点。此外,zookeeper还可以进行IP网段的控制,例如:IP:192.168.0.1/24,表示IP地址如果匹配192.168.0.1的前24位就可以访问zookeeper的数据节点。
2.Digest
这是最常用的权限控制模式,以一种“username:password”的方式来控制权限。例如对一个节点设置“digest:lidihao:123456”,则一个会话只用用“digest:lidihao:123456”才能访问zookeeper的节点。
3.world
设置该权限模式的节点对所有用户是开发的。该模式只有一个授权ID,即“anyone”
4.super
超级用户,一种特殊的Digest模式,可以对zookeeper上任意节点进行任何操作。 - 授权对象:ID
授权对象指的是权限赋予的用户或一个指定实体。不同的权限模式,授权对象不同。
- 权限:Permission
有五类权限:cdrwa
CREATE(C):数据节点的创建权限,允许授权对象在该数据节点下创建子节点
DELETE(D):子节点的删除权限,允许授权对象删除数据节点的子节点
READ(R):数据节点的读取权限,允许授权对象访问该数据节点的子节点列表和节点的数据
WRITE(W):数据节点的更新权限,允许授权对象对该数据节点进行更新操作
ADMIN(A):数据节点的管理权限,允许授权对象设置该节点的ACL
代码演示
//设置ip权限,允许特定的IP访问zookeeper的节点
@Test
public void setACL() throws IOException, KeeperException, InterruptedException {
ZooKeeper zooKeeper=new ZooKeeper("192.168.175.130:2181,192.168.175.129:2181,192.168.175.133:2181",5000,null);
Id id=new Id("ip","192.168.175.0/16");
ACL acl=new ACL(ZooDefs.Perms.READ,id);
List<ACL> aclList=new ArrayList<ACL>();
aclList.add(acl);
zooKeeper.create("/ip","ip schema".getBytes(),aclList, CreateMode.PERSISTENT);
TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
}
@Test
public void getData() throws IOException, KeeperException, InterruptedException {
ZooKeeper zooKeeper=new ZooKeeper("192.168.175.130:2181,192.168.175.129:2181,192.168.175.133:2181",5000,null);
byte[] datas=zooKeeper.getData("/ip",null,null);
System.out.println(new String(datas,0,datas.length));
TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
}
//设置zookeeper数据节点的权限
@Test
public void setACLDigest() throws IOException, KeeperException, InterruptedException, NoSuchAlgorithmException {
ZooKeeper zooKeeper=new ZooKeeper("192.168.175.130:2181,192.168.175.129:2181,192.168.175.133:2181",5000,null);
//第一种方法
Id id=new Id("digest", DigestAuthenticationProvider.generateDigest("lidihao:123"));
ACL acl=new ACL(ZooDefs.Perms.READ,id);
List<ACL> aclList=new ArrayList<ACL>();
aclList.add(acl);
zooKeeper.create("/digest1","digest schema".getBytes(),aclList, CreateMode.PERSISTENT);
//第二种方法
zookeeper.addAuth("digest","lidihao:123".getBytes());
zooKeeper.create("/digest1","digest schema".getBytes(),Ids.CREATEOR_ALL_ACL, CreateMode.PERSISTENT);
//第二种方法不用将密码加密
TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
}
@Test
public void getDataDigest() throws IOException, KeeperException, InterruptedException {
ZooKeeper zooKeeper=new ZooKeeper("192.168.175.130:2181,192.168.175.129:2181,192.168.175.133:2181",5000,null);
zooKeeper.addAuthInfo("digest","lidihao:123".getBytes());
byte[] datas=zooKeeper.getData("/digest1",null,null);
System.out.println(new String(datas,0,datas.length));
TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
}