ApsaraMQ for MQTT supports token-based authentication for controlling client access to messaging resources. This topic describes how to set connection parameters with tokens, update tokens without disconnecting, and handle token expiration and invalidation notifications.
Authentication flow
Token-based authentication follows this sequence:
Your application requests tokens from the ApsaraMQ for MQTT token service, specifying the resources and permission types (read, write, or both).
The MQTT client connects to the broker with the token data in the CONNECT packet's
UsernameandPasswordfields.The broker verifies the token and grants access to the specified resources.
During the session, the client can update tokens by publishing to a system topic, and the broker pushes notifications for token expiration or invalidation.
Token types
Each ApsaraMQ for MQTT client can hold one token per type and may use one or more types simultaneously.
| Type identifier | Permission | Description |
|---|---|---|
| R | Read-only | Grants read permission for the specified resources |
| W | Write-only | Grants write permission for the specified resources |
| RW | Read and write | Grants both read and write permissions for the specified resources |
Connection parameters
To connect with token-based authentication, set the Username and Password fields in the MQTT CONNECT packet as follows.
Username
Format: Token|<AccessKey ID>|<Instance ID>
| Component | Description |
|---|---|
Token | The literal string Token, indicating token-based authentication mode |
<AccessKey ID> | Your Alibaba Cloud AccessKey ID |
<Instance ID> | Your ApsaraMQ for MQTT instance ID |
Example:
For a client with ID GID_Test@@@0001, instance ID mqtt-xxxxx, and AccessKey ID YYYYY:
Token|YYYYY|mqtt-xxxxxPassword
Format: Token type and content pairs concatenated with vertical bars (|). Multiple token types can appear in any order.
Examples:
Single token: If the client holds a read-only token
123, set Password to:R|123Multiple tokens: If the client holds a read-only token
123and a write-only tokenabcd, set Password to:R|123|W|abcd
All tokens in the Password field must be valid. If any token is invalid, the broker may reject the connection.
Update tokens without disconnecting
By default, to rotate a token, disconnect the client and reconnect with the new token. To avoid disconnection, publish a token update message to the system topic $SYS/uploadToken. The broker replaces the token in its session without dropping the connection.
Update procedure
Publish a JSON message to
$SYS/uploadTokenwith the new token content.Wait for the PUBACK response before performing any publish or subscribe operations. If the client proceeds without waiting, the broker may still authenticate with the old token, causing an authentication failure and disconnection.
Update the local token configuration so the client uses the new token on the next reconnection.
Message format
Topic: $SYS/uploadToken
Payload: JSON string with the following fields:
| Parameter | Type | Required | Description |
|---|---|---|---|
| token | String | Yes | The new token string |
| type | String | Yes | Token type: R, W, or RW. An invalid type causes a permission verification error. |
Example payload:
{
"token": "<your-token-string>",
"type": "RW"
}Response: A standard PUBACK message.
Always update the local token configuration after a successful token update. Otherwise, the client may use the old token data during the next reconnection.
Token expiration notifications
The ApsaraMQ for MQTT broker pushes expiration warnings to clients through the system topic $SYS/tokenExpireNotice. No subscription is required -- the broker delivers these notifications directly.
Topic: $SYS/tokenExpireNotice
Payload: JSON string with the following fields:
| Parameter | Type | Description |
|---|---|---|
| expireTime | Long | Token expiration time as a Unix timestamp in milliseconds |
| type | String | Token type: R, W, or RW |
Notification behavior
The broker typically sends a notification approximately 5 minutes before a token expires.
Delivery is not guaranteed. Do not rely solely on these notifications for token lifecycle management.
After receiving a notification, request a new token and update it promptly to avoid messaging failures.
Token invalidation notifications
When the broker detects a token verification error, it pushes an error notification to the client through the system topic $SYS/tokenInvalidNotice and then disconnects the client. No subscription is required.
Topic: $SYS/tokenInvalidNotice
Payload: JSON string with the following fields:
| Parameter | Type | Description |
|---|---|---|
| code | int | Error code that identifies the type of token verification failure |
| type | String | Token type: R, W, or RW |
Error codes
| Code | Description |
|---|---|
| 1 | The token is forged and cannot be parsed |
| 2 | The token has expired |
| 3 | The token has been revoked |
| 4 | The resource and token do not match |
| 5 | The permission type and token do not match |
| 8 | The signature is invalid |
| -1 | The account permission is invalid |
Disconnection behavior
When the broker encounters a token verification error:
Authentication fails.
The broker pushes the error code to the client through
$SYS/tokenInvalidNotice.The broker disconnects the client.
Use the error code to identify the root cause and take corrective action before reconnecting.
Best practices
Use short-lived tokens. Set a reasonable validity period for tokens to limit the impact of token leakage.
Enable TLS. Encrypt client connections to prevent token interception during transmission.
Handle expiration proactively. Implement token refresh logic in your client rather than relying solely on broker expiration notifications, because delivery is not guaranteed.
Store credentials securely. Retrieve your AccessKey ID from environment variables or a secrets manager instead of hardcoding it in your application.
Keep local and broker tokens in sync. After updating a token through
$SYS/uploadToken, always update the local configuration to prevent stale tokens on reconnection.