JWT Authorization
JWT Authorization provides a secure way of quering NanoMQ' HTTP APIs.
Building
JWT is an extended feature in NanoMQ, it is disabled by default. To enable JWT with cmake option -DENABLE_JWT=ON
:
$ cmake -DENABLE_JWT=ON ..
$ make
Generate a public and private key file
Before issuing JWT, it's necessary to generate a pair of public and private keys.
Note: The public key file name is the issuing name.
Generate RSA keys using OpenSSL command-line tools:
# generate private key
$ openssl genrsa -out nanomq.key 2048
# generate public key
$ openssl rsa -in nanomq.key -out nanomq.pub -pubout
Configuration
The default authorization mode is Basic
, you need to change the auth_type
to JWT
in the configuration file and specify the path to JWT
public key file.
Start NanoMQ
Start NanoMQ and specify the path to the configuration path.
$ nanomq start --conf ./nanomq.conf
If you are using the KV format, start NanoMQ with the command below:
$ nanomq start --conf ./nanomq_old.conf
Token rules
Generate a token for HTTP client;
The required JWT structure for NanoMQ is as follows:
header
{
"alg": "RS256",
"typ": "JWT"
}
payload
{
"iss": "nanomq.pub",
"iat": "1683281256",
"exp": "1683283256",
"bodyEncode": "0"
}
Header
- typ: Using JWT
- alg: Using RS256
Payload
- iss: Defined it according to the requirements, but ensure that it is consistent with the filename of the generated public key file. For example, if the file name is "nanomq.pub", the
iss
should benanomq.pub
. - iat: Time of issuance.
- exp: Expiration time of issuance.
Token generation
You can use JWT official website tool to generate a JWT. Fill in the Decoded section as follows:
- Algorithm: RS256
- Header: Header
- Payload: Payload
- Verify Signature: Fille in public and private key.
Send Request to NanoMQ HTTP Server
Use curl
to send a GET
request with the generated token to NanoMQ HTTP Server :
$ curl --location 'http://127.0.0.1:8081/api/v4' \
--header 'Authorization: Bearer {TOKEN}'