tonglin0325的个人主页

Zk学习笔记——权限控制

参考:从Paxos到Zookeeper分布式一致性原理和实践

使用的zk依赖是cdh5.16.2的3.4.5

1
2
3
4
5
6
7
<!-- zookeeper -->
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.5-cdh5.16.2</version>
</dependency>

Zookeeper提供了多种权限控制模式,分别是world,auth,digest,ip和super。

下面介绍模式scheme中的digest

使用如下语句对zk session添加权限,其中的username:password是账号密码

1
2
zk1.addAuthInfo("digest", "username:password".getBytes());

如果操作zk节点没有权限的话,会抛出NoAuthException

1
2
Exception in thread "main" org.apache.zookeeper.KeeperException$NoAuthException: KeeperErrorCode = NoAuth for /app6

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.bigdata.zookeeper;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;

public class AuthExample {

private static ZooKeeper zk1;
private static ZooKeeper zk2;

public static void main(String[] args) throws Exception {
// zk1 session
zk1 = new ZooKeeper("master:2181", 5000, null);
zk1.addAuthInfo("digest", "username:password".getBytes());
// 创建一个节点
String path = "/app6";
zk1.create(path, "123".getBytes(), ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.EPHEMERAL);

// zk2 session无权限
zk2 = new ZooKeeper("master:2181", 5000, null);
// System.out.println(new String(zk2.getData(path, false, null)));

// zk2 session有权限
zk2.addAuthInfo("digest", "username:password".getBytes());
System.out.println(new String(zk2.getData(path, false, null)));
}

}

没有权限的话,zkui也会报错

使用zookeeper-client访问

1
2
3
lintong@master:/opt/cloudera/parcels/CDH/bin$ ./zookeeper-client
Connecting to localhost:2181

查看,仍然没有权限

1
2
3
4
5
[zk: localhost:2181(CONNECTED) 0] ls /
[cluster, controller, brokers, zookeeper, admin, isr_change_notification, log_dir_event_notification, ngdata, controller_epoch, kafka-manager, solr, app6, consumers, hive_zookeeper_namespace_hive, latest_producer_id_block, app2, config, app1, hbase, app4, app3]
[zk: localhost:2181(CONNECTED) 1] ls /app6
Authentication is not valid : /app6

设置密码并查看

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[zk: localhost:2181(CONNECTED) 3] addauth digest username:password

[zk: localhost:2181(CONNECTED) 7] get /app6
123
cZxid = 0x139e88
ctime = Sun Aug 02 23:38:30 CST 2020
mZxid = 0x139e88
mtime = Sun Aug 02 23:38:30 CST 2020
pZxid = 0x139e88
cversion = 0
dataVersion = 0
aclVersion = 0
ephemeralOwner = 0x0
dataLength = 3
numChildren = 0