Pulsar 基于 JSON Web Tokens (RFC-7519) 提供了一个标准的 JWT 客户端,可以生成密钥、制作 token 和检测密钥有效性等功能。

Step 1. 生成 secret key

bin/pulsar tokens create-secret-key --output my-secret.key

Step 2. 生成用于超级管理员的 token

我们将超级管理员命名为 admin(对应 pulsar 认证概念里对 role)。这里不指定超时时间( --expiry-time),则默认将不过期。

bin/pulsar tokens create --secret-key my-secret.key --subject admin
eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbiJ9.Ra9pwWHTWjB67v5GkVuuDMqXWwfeTJuwflyvmhxYk_c

Step 3. 生成给测试用户的 token

bin/pulsar tokens create --secret-key my-secret.key --subject test-user --expiry-time 7d
eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0LXVzZXIiLCJleHAiOjE2NTY3NzYwOTh9.awbp6DreQwUyV8UCkYyOGXCFbfo4ZoV-dofXYTnFXO8

Step 4. 配置 broker

# 开启认证
authenticationEnabled=true
# 认证提供者
authenticationProviders=org.apache.pulsar.broker.authentication.AuthenticationProviderToken
# 开启授权
authorizationEnabled=true
# 超级管理员
superUserRoles=admin
# broker Client 使用等认证插件
brokerClientAuthenticationPlugin=org.apache.pulsar.client.impl.auth.AuthenticationToken
# broker Client 通讯使用的 token(需要 admin role)
brokerClientAuthenticationParameters={"token":"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbiJ9.Ra9pwWHTWjB67v5GkVuuDMqXWwfeTJuwflyvmhxYk_c"}
# 使用 secretKey 的密钥文件位置(file://开头)
tokenSecretKey=file:///Users/futeng/workspace/github/futeng/pulsar-pseudo-cluster/pulsar-1/my-secret.key

Step 5. 重启 broker

bin/pulsar-daemon stop broker
bin/pulsar-daemon start broker

Step 6. 测试

Step 6.1. 验证 broker token

bin/pulsar tokens validate -sk  /Users/futeng/workspace/github/futeng/pulsar-pseudo-cluster/pulsar-1/my-secret.key -i "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbiJ9.Ra9pwWHTWjB67v5GkVuuDMqXWwfeTJuwflyvmhxYk_c"

# 打印:{sub=admin}

Step 6.2. 测试超级管理员用户访问

# produce as admin role
bin/pulsar-client \\\\
--url "pulsar://127.0.0.1:6650" \\\\
--auth-plugin "org.apache.pulsar.client.impl.auth.AuthenticationToken" \\\\
--auth-params {"token":"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbiJ9.Ra9pwWHTWjB67v5GkVuuDMqXWwfeTJuwflyvmhxYk_c"} \\\\
produce public/default/test -m "hello pulsar" -n 10

Step 6.3. 测试普通用户访问