Secure authentication with tokens
Updated
Retrieve tokens generated by an authentication token server to securely connect to Agora channels.
To protect your business, it is best practice to authenticate every client that joins a channel. This guide explains how to fetch an authentication token from your token server, use it to join a channel, and handle token errors.
Understand the tech
When a device attempts to connect to an Agora channel, your app retrieves a token from the token server in your security infrastructure. Your app then sends this token to Agora SDRTN® for authentication. Agora SDRTN® reads the information stored in the token to validate the request.
Token authentication flow
Prerequisites
Before starting, ensure that you have:
-
Implemented the basic IoT SDK functionality. See Build from scratch.
-
Deployed a token server using either of the following guides:
Implement basic authentication
This section shows you how to implement basic authentication by acquiring a token and using it to join a channel.
Use a token to join a channel
The device requests a token from your authentication server corresponding to the user ID and the channel name it intends to join. You use the received token to join a channel by passing it to agora_rtc_join_channel, along with the connection ID, channel name, and user ID:
// Join a channel
rval = agora_rtc_join_channel(g_conn_id, DEFAULT_CHANNEL_NAME, DEFAULT_USER_ID, p_token, &channel_options);
if (rval < 0) {
printf("Failed to join channel \"%s\", reason: %s\n", DEFAULT_CHANNEL_NAME, agora_rtc_err_2_str(rval));
return -1;
}The user ID and channel name used to join a channel must be consistent with the values used to generate the token.
Handle token errors
If a token is invalid, expired, or missing when required, IoT SDK triggers the on_error callback with a token-related error code. Handle these codes to detect authentication failures and fetch a fresh token from your token server:
static void __on_error(connection_id_t conn_id, int code, const char *msg) {
if (code == ERR_INVALID_TOKEN || code == ERR_TOKEN_EXPIRED) {
printf("Invalid token. Please double check. Error msg \"%s\"\n", msg);
} else if (code == ERR_DYNAMIC_TOKEN_BUT_USE_STATIC_KEY) {
printf("Dynamic token is enabled but is not provided. Error msg \"%s\"\n", msg);
} else {
printf("Error %d is captured. Error msg \"%s\"\n", code, msg);
}
}To recover from a token error, request a new token from your token server, then call agora_rtc_join_channel again with the fresh token. For a full list of token and other error codes, see Error codes.
Renew a token
To renew a token before it expires, without rejoining the channel, request a new token from your token server and pass it to agora_rtc_renew_token.
Reference
This section contains content that completes the information on this page, or points you to documentation that explains other aspects to this product.
