All Products
Search
Document Center

ApsaraMQ for MQTT:Client operations for token-based authentication

Last Updated:Mar 11, 2026

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:

  1. Your application requests tokens from the ApsaraMQ for MQTT token service, specifying the resources and permission types (read, write, or both).

  2. The MQTT client connects to the broker with the token data in the CONNECT packet's Username and Password fields.

  3. The broker verifies the token and grants access to the specified resources.

  4. 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 identifierPermissionDescription
RRead-onlyGrants read permission for the specified resources
WWrite-onlyGrants write permission for the specified resources
RWRead and writeGrants 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>

ComponentDescription
TokenThe 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-xxxxx

Password

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|123
  • Multiple tokens: If the client holds a read-only token 123 and a write-only token abcd, set Password to:

      R|123|W|abcd
Important

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

  1. Publish a JSON message to $SYS/uploadToken with the new token content.

  2. 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.

  3. 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:

ParameterTypeRequiredDescription
tokenStringYesThe new token string
typeStringYesToken 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.

Important

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:

ParameterTypeDescription
expireTimeLongToken expiration time as a Unix timestamp in milliseconds
typeStringToken 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:

ParameterTypeDescription
codeintError code that identifies the type of token verification failure
typeStringToken type: R, W, or RW

Error codes

CodeDescription
1The token is forged and cannot be parsed
2The token has expired
3The token has been revoked
4The resource and token do not match
5The permission type and token do not match
8The signature is invalid
-1The account permission is invalid

Disconnection behavior

When the broker encounters a token verification error:

  1. Authentication fails.

  2. The broker pushes the error code to the client through $SYS/tokenInvalidNotice.

  3. 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.