Skip to content

JWT 认证 ​

JSON Web Token(JWT)认证通过签名 Token 为访问 EMQX Edge HTTP API 提供安全机制。它支持与外部身份系统集成,并确保只有经过认证的用户才能访问 Broker 的管理端点。

生成公钥和私钥 ​

签发 JWT 前,必须使用 OpenSSL 生成一对 RSA 密钥:

注意:JWT 中的 iss(issuer)声明必须与公钥文件名一致。

bash
# generate private key
$ openssl genrsa -out nanomq.key 2048
# generate public key
$ openssl rsa -in nanomq.key -out nanomq.pub -pubout

配置 ​

JWT 是 EMQX Edge 中的可选功能,默认禁用。默认 HTTP server 认证模式为 basic。要启用 JWT 认证,请设置 auth_type = jwt,并在配置文件中提供公钥路径。

在 nanomq.conf 中使用以下 HOCON 配置。变更会在重启 EMQX Edge 后生效。

完整配置选项请参见 HTTP Server 配置。

c
http_server {
    # # http server port
    # #
    # # Value: 0 - 65535
    port = 8081
    # # parallel for http server
    # # Handle a specified maximum number of outstanding requests
    # #
    # # Value: 1-infinity
    parallel = 32
    # # http server username
    # #
    # # Value: String
    username = admin
    # # http server password
    # #
    # # Value: String
    password = public
    # # http server auth type
    # # If set auth_type=jwt, make sure you have built JWT dependency with `-DENABLE_JWT=ON` first.
    # #
    # # Value: String basic | jwt
    auth_type = jwt
    jwt {
        # # http server jwt public key file
        # # Used together with 'http_server.auth_type=jwt',
        # # Path to the file containing the user's private key.
        # #
        # # Value: File
        public.keyfile = "/etc/certs/jwt/nanomq.pub"
    }
}

使用 JWT 配置启动 EMQX Edge ​

要使用自定义配置文件启动 EMQX Edge,请运行:

bash
emqx-edge start --conf path/to/nanomq.conf

请将 path/to/nanomq.conf 替换为你的配置文件实际路径。

JWT Token 格式 ​

要为 HTTP 客户端生成 Token,EMQX Edge 的有效 JWT 必须包含以下结构:

bash
header
{
    "alg": "RS256",
    "typ": "JWT"
}

payload
{
    "iss": "nanomq.pub",
    "iat": "1683281256",
    "exp": "1683283256",
    "bodyEncode": "0"
}

Header 字段 ​

  • typ:必须为 JWT
  • alg:必须为 RS256(RSA SHA-256)

Payload 字段 ​

  • iss:必须与公钥文件名一致。例如,如果文件名为 nanomq.pub,则 iss 应为 nanomq.pub。
  • iat:签发时间戳,单位为秒。
  • exp:过期时间戳,单位为秒。
  • bodyEncode:设置为 0(具体用途取决于实现,可选)。

生成 Token ​

你可以使用 JWT 官方网站工具生成 JWT。在 Decoded 区域中填写:

  • Algorithm:RS256
  • Header:Header
  • Payload:Payload
  • Verify Signature:填写公钥和私钥。

使用 JWT 向 EMQX Edge HTTP Server 发送请求 ​

使用 curl 携带生成的 Token 向 EMQX Edge HTTP Server 发送 GET 请求:

bash
$ curl --location 'http://127.0.0.1:8081/api/v4' \
--header 'Authorization: Bearer {TOKEN}'

将 {TOKEN} 替换为签名后的 JWT 字符串。