Skip to main content

You are looking at Voice Calling v3.x Docs. The newest version is  Voice Calling 4.x

Android
iOS
macOS
Windows C++
Windows C#
Unity
Flutter
React Native
Electron
Cocos Creator
Cocos2d-x

Upgrade from AccessToken to AccessToken2

This section introduces how to use AccessToken to authenticate your users and how to upgrade from AccessToken to AccessToken2.

If you have never used AccessToken before, you can skip this article and refer to Authenticate Your Users with Tokens.

Authenticate your users with AccessToken

Understand the tech

The following figure shows the steps in the authentication flow:

token authentication flow

A token is a dynamic key generated on your app server that is valid for a maximum of 24 hours. When your users connect to an Agora channel from your app client, Agora Platform validates the token and reads the user and project information stored in the token. A token contains the following information:

  • The App ID of your Agora project
  • The channel name
  • The user ID of the user to be authenticated
  • The privilege of the user, either as a publisher or a subscriber
  • The time after which the token expires

Prerequisites

In order to follow this procedure you must have the following:

Implement the authentication flow

This section shows you how to supply and consume a token that gives rights to specific functionality to authenticated users using the source code provided by Agora.

Get the App ID and App Certificate

This section shows you how to get the security information needed to generate a token, including the App ID and App Certificate of your project.

1. Get the App ID

Agora automatically assigns each project an App ID as a unique identifier.

To copy this App ID, find your project on the Project Management page in Agora Console, and click the copy icon in the App ID column.

2. Get the App Certificate

To get an App Certificate, do the following:

  1. On the Project Management page, click Config for the project you want to use. 1641971710869
  2. Click the copy icon under Primary Certificate. 1637660100222

Deploy a token server

Token generators create the tokens requested by your client app to enable secure access to Agora Platform. To serve these tokens you deploy a generator in your security infrastructure.

In order to show the authentication workflow, this section shows how to build and run a token server written in Golang on your local machine.

This sample server is for demonstration purposes only. Do not use it in a production environment.
  1. Create a file, server.go, with the following content. Then replace <Your App ID> and <Your App Certificate> with your App ID and App Certificate.

    package main

    import (
    rtctokenbuilder "github.com/AgoraIO/Tools/DynamicKey/AgoraDynamicKey/go/src/RtcTokenBuilder"
    "fmt"
    "log"
    "net/http"
    "time"
    "encoding/json"
    "errors"
    "strconv"
    )

    type rtc_int_token_struct struct{
    Uid_rtc_int uint32 `json:"uid"`
    Channel_name string `json:"ChannelName"`
    Role uint32 `json:"role"`
    }

    var rtc_token string
    var int_uid uint32
    var channel_name string

    var role_num uint32
    var role rtctokenbuilder.Role

    // Use RtcTokenBuilder to generate an <Vg k="VSDK" /> token.
    func generateRtcToken(int_uid uint32, channelName string, role rtctokenbuilder.Role){

    appID := "<Your App ID>"
    appCertificate := "<Your App Certificate>"
    // Number of seconds after which the token expires.
    // For demonstration purposes the expiry time is set to 40 seconds. This shows you the automatic token renew actions of the client.
    expireTimeInSeconds := uint32(40)
    // Get current timestamp.
    currentTimestamp := uint32(time.Now().UTC().Unix())
    // Timestamp when the token expires.
    expireTimestamp := currentTimestamp + expireTimeInSeconds

    result, err := rtctokenbuilder.BuildTokenWithUID(appID, appCertificate, channelName, int_uid, role, expireTimestamp)
    if err != nil {
    fmt.Println(err)
    } else {
    fmt.Printf("Token with uid: %s\n", result)
    fmt.Printf("uid is %d\n", int_uid )
    fmt.Printf("ChannelName is %s\n", channelName)
    fmt.Printf("Role is %d\n", role)
    }
    rtc_token = result
    }


    func rtcTokenHandler(w http.ResponseWriter, r *http.Request){
    w.Header().Set("Content-Type", "application/json; charset=UTF-8")
    w.Header().Set("Access-Control-Allow-Origin", "*")
    w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS");
    w.Header().Set("Access-Control-Allow-Headers", "*");

    if r.Method == "OPTIONS" {
    w.WriteHeader(http.StatusOK)
    return
    }

    if r.Method != "POST" && r.Method != "OPTIONS" {
    http.Error(w, "Unsupported method. Please check.", http.StatusNotFound)
    return
    }


    var t_int rtc_int_token_struct
    var unmarshalErr *json.UnmarshalTypeError
    int_decoder := json.NewDecoder(r.Body)
    int_err := int_decoder.Decode(&t_int)
    if (int_err == nil) {

    int_uid = t_int.Uid_rtc_int
    channel_name = t_int.Channel_name
    role_num = t_int.Role
    switch role_num {
    case 0:
    // DEPRECATED. RoleAttendee has the same privileges as RolePublisher.
    role = rtctokenbuilder.RoleAttendee
    case 1:
    role = rtctokenbuilder.RolePublisher
    case 2:
    role = rtctokenbuilder.RoleSubscriber
    case 101:
    // DEPRECATED. RoleAdmin has the same privileges as RolePublisher.
    role = rtctokenbuilder.RoleAdmin
    }
    }
    if (int_err != nil) {

    if errors.As(int_err, &unmarshalErr){
    errorResponse(w, "Bad request. Wrong type provided for field " + unmarshalErr.Value + unmarshalErr.Field + unmarshalErr.Struct, http.StatusBadRequest)
    } else {
    errorResponse(w, "Bad request.", http.StatusBadRequest)
    }
    return
    }

    generateRtcToken(int_uid, channel_name, role)
    errorResponse(w, rtc_token, http.StatusOK)
    log.Println(w, r)
    }

    func errorResponse(w http.ResponseWriter, message string, httpStatusCode int){
    w.Header().Set("Content-Type", "application/json")
    w.Header().Set("Access-Control-Allow-Origin", "*")
    w.WriteHeader(httpStatusCode)
    resp := make(map[string]string)
    resp["token"] = message
    resp["code"] = strconv.Itoa(httpStatusCode)
    jsonResp, _ := json.Marshal(resp)
    w.Write(jsonResp)

    }

    func main(){
    // Handling routes
    // Video Calling token from Video SDK num uid
    http.HandleFunc("/fetch_rtc_token", rtcTokenHandler)
    fmt.Printf("Starting server at port 8082\n")

    if err := http.ListenAndServe(":8082", nil); err != nil {
    log.Fatal(err)
    }
    }
    Copy
  2. A go.mod file defines this module’s import path and dependency requirements. To create the go.mod for your token server, run the following command:

    $ go mod init sampleServer
    Copy
  3. Get dependencies by running the following command:

    $ go get
    Copy
  4. Start the server by running the following command:

    $ go run server.go
    Copy

Use tokens for user authentication

This section uses the Web client as an example to show how to use a token for client-side user authentication.

In order to show the authentication workflow, this section shows how to build and run a Web client on your local machine.

This sample client is for demonstration purposes only. Do not use it in a production environment.
  1. Create the project structure of the Web client with a folder including the following files.

    • index.html: User interface
    • client.js: App logic with Agora Video Calling Web SDK 4.x
    |
    |-- index.html
    |-- client.js
    Copy
  2. In index.html, add the following code to include the app logic in the UI:

    <html>
    <head>
    <title>Token demo</title>
    </head>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <body>
    <h1>Token demo</h1>

    <script src="https://download.agora.io/sdk/release/AgoraRTC_N.js"></script>
    <script src="./client.js"></script>

    </body>
    </html>
    Copy
  3. Create the app logic by editing client.js with the following content. Then replace <Your App ID> with your App ID. The App ID must match the one in the server. You also need to replace <Your Host URL and port> with the host URL and port of the local Golang server you have just deployed, such as 10.53.3.234:8082.

    var rtc = {
    // For the local audio and video tracks.
    localAudioTrack: null,
    localVideoTrack: null,
    };

    var options = {
    // Pass your app ID here.
    appId: "<Your app ID>",
    // Set the channel name.
    channel: "ChannelA",
    // Set the user role in the channel.
    role: "host"
    };

    // Fetch a token from the Golang server.
    function fetchToken(uid, channelName, tokenRole) {

    return new Promise(function (resolve) {
    axios.post('http://<Your Host URL and port>/fetch_rtc_token', {
    uid: uid,
    channelName: channelName,
    role: tokenRole
    }, {
    headers: {
    'Content-Type': 'application/json; charset=UTF-8'
    }
    })
    .then(function (response) {
    const token = response.data.token;
    resolve(token);
    })
    .catch(function (error) {
    console.log(error);
    });
    })
    }

    async function startBasicCall() {

    const client = AgoraRTC.createClient({ mode: "live", codec: "vp8" });
    client.setClientRole(options.role);
    const uid = 123456;

    // Fetch a token before calling join to join a channel.
    let token = await fetchToken(uid, options.channel, 1);

    await client.join(options.appId, options.channel, token, uid);
    rtc.localAudioTrack = await AgoraRTC.createMicrophoneAudioTrack();
    rtc.localVideoTrack = await AgoraRTC.createCameraVideoTrack();
    await client.publish([rtc.localAudioTrack, rtc.localVideoTrack]);
    const localPlayerContainer = document.createElement("div");
    localPlayerContainer.id = uid;
    localPlayerContainer.style.width = "640px";
    localPlayerContainer.style.height = "480px";
    document.body.append(localPlayerContainer);

    rtc.localVideoTrack.play(localPlayerContainer);

    console.log("publish success!");

    client.on("user-published", async (user, mediaType) => {
    await client.subscribe(user, mediaType);
    console.log("subscribe success");

    if (mediaType === "video") {
    const remoteVideoTrack = user.videoTrack;
    const remotePlayerContainer = document.createElement("div");
    remotePlayerContainer.textContent = "Remote user " + user.uid.toString();
    remotePlayerContainer.style.width = "640px";
    remotePlayerContainer.style.height = "480px";
    document.body.append(remotePlayerContainer);
    remoteVideoTrack.play(remotePlayerContainer);

    }

    if (mediaType === "audio") {
    const remoteAudioTrack = user.audioTrack;
    remoteAudioTrack.play();
    }

    client.on("user-unpublished", user => {
    const remotePlayerContainer = document.getElementById(user.uid);
    remotePlayerContainer.remove();
    });

    });

    // When token-privilege-will-expire occurs, fetch a new token from the server and call renewToken to renew the token.
    client.on("token-privilege-will-expire", async function () {
    let token = await fetchToken(uid, options.channel, 1);
    await client.renewToken(token);
    });

    // When token-privilege-did-expire occurs, fetch a new token from the server and call join to rejoin the channel.
    client.on("token-privilege-did-expire", async function () {
    console.log("Fetching the new Token")
    let token = await fetchToken(uid, options.channel, 1);
    console.log("Rejoining the channel with new Token")
    await client.join(options.appId, options.channel, token, uid);
    });

    }

    startBasicCall()
    Copy

    In the code example, you can see that token is related to the following code logic in the client:

    • Call join to join the channel with token, uid, and channel name. The uid and channel name must be the same as the ones used to generate the token.
    • The token-privilege-will-expire callback occurs 30 seconds before a token expires. When the token-privilege-will-expire callback is triggered,the client must fetch the token from the server and call renewToken to pass the new token to the SDK.
    • The token-privilege-did-expire callback occurs when a token expires. When the token-privilege-did-expire callback is triggered, the client must fetch the token from the server and call join to use the new token to join the channel.
  4. Open index.html with a supported browser to perform the following actions:

    • Successfully joining a channel.
    • Renewing a token every 10 seconds.

Reference

This section introduces token generator libraries, version requirements, and related documents about tokens.

Token generator libraries

Agora provides an open-source AgoraDynamicKey repository on GitHub, which enables you to generate tokens on your server with programming languages such as C++, Java, and Go.

LanguageAlgorithmCore methodSample code
C++HMAC-SHA256buildTokenWithUidRtcTokenBuilderSample.cpp
GoHMAC-SHA256buildTokenWithUidsample.go
JavaHMAC-SHA256buildTokenWithUidRtcTokenBuilderSample.java
Node.jsHMAC-SHA256buildTokenWithUidRtcTokenBuilderSample.js
PHPHMAC-SHA256buildTokenWithUidRtcTokenBuilderSample.php
PythonHMAC-SHA256buildTokenWithUidRtcTokenBuilderSample.py
Python3HMAC-SHA256buildTokenWithUidRtcTokenBuilderSample.py

API reference

This section introduces the parameters and descriptions for the method to generate a token. Take C++ as an example:

static std::string buildTokenWithUid(
const std::string& appId,
const std::string& appCertificate,
const std::string& channelName,
uint32_t uid,
UserRole role,
uint32_t privilegeExpiredTs = 0);
Copy
ParameterDescription
appIdThe App ID of your Agora project.
appCertificateThe App Certificate of your Agora project.
channelNameThe channel name. The string length must be less than 64 bytes. Supported character scopes are:
  • All lowercase English letters: a to z.
  • All upper English letters: A to Z.
  • All numeric characters: 0 to 9.
  • The space character.
  • Punctuation characters and other symbols, including: "!", "#", "$", "%", "&", "(", ")", "+", "-", ":", ";", "<", "=", ".", ">", "?", "@", "[", "]", "^", "_", " , ", "|", "~", ",".
uidThe user ID of the user to be authenticated. A 32-bit unsigned integer with a value range from 1 to (2³² - 1). It must be unique. Set uid as 0, if you do not want to authenticate the user ID, that is, any uid from the app client can join the channel.
roleThe privilege of the user, either as a publisher or a subscriber. This parameter determines whether a user can publish streams in the channel.
  • Role_Publisher(1): (Default) The user has the privilege of a publisher, that is, the user can publish streams in the channel.
  • Role_Subscriber(2): The user has the privilege of a subscriber, that is, the user can only subscribe to streams, not publish them, in the channel.
This value takes effect only if you have enabled co-host authentication. For details, see FAQ How do I use co-host authentication.
privilegeExpiredTsThe Unix timestamp (s) when the token expires, represented by the sum of the current timestamp and the valid time of the token. For example, if you set privilegeExpiredTs as the current timestamp plus 600 seconds, the token expires in 10 minutes. A token is valid for 24 hours at most. If you set this parameter as 0 or a period longer than 24 hours, the token is still valid for 24 hours.

Upgrade from AccessToken to AccessToken2

Update the token server

  1. Replace the rtctokenbuilder import statement, and remove the "time" import statement:

    import (
    // Replace
    // rtctokenbuilder "github.com/AgoraIO/Tools/DynamicKey/AgoraDynamicKey/go/src/RtcTokenBuilder"
    rtctokenbuilder "github.com/AgoraIO/Tools/DynamicKey/AgoraDynamicKey/go/src/rtctokenbuilder2"
    "fmt"
    "log"
    "net/http"
    // Remove
    // "time"
    "encoding/json"
    "errors"
    "strconv"
    )
    Copy
  2. Remove the timestamp generation statements. Add tokenExpireTimeInSeconds and privilegeExpireTimeInSeconds:

    // expireTimeInSeconds := uint32(40)
    // Gets current timestamp.
    // currentTimestamp := uint32(time.Now().UTC().Unix())
    // Timestamp when the token expires.
    // expireTimestamp := currentTimestamp + expireTimeInSeconds
    tokenExpireTimeInSeconds := uint32(40)
    privilegeExpireTimeInSeconds := uint32(40)
    Copy
  3. Update the token builder function:

    // Before
    // result, err := rtctokenbuilder.BuildTokenWithUID(appID, appCertificate, channelName, int_uid, role, expireTimestamp)
    // After
    // Update BuildTokenWithUID with BuildTokenWithUid
    // Update expireTimestamp with tokenExpireTimeInSeconds and privilegeExpireTimeInSeconds
    result, err := rtctokenbuilder.BuildTokenWithUid(appID, appCertificate, channelName, int_uid, role, tokenExpireTimeInSeconds, privilegeExpireTimeInSeconds)
    Copy
  4. Remove unsupported roles:

    switch role_num {
    // Remove
    // case 0:
    // DEPRECATED. RoleAttendee has the same privileges as RolePublisher.
    // role = rtctokenbuilder.RoleAttendee
    case 1:
    role = rtctokenbuilder.RolePublisher
    case 2:
    role = rtctokenbuilder.RoleSubscriber
    // Remove
    // case 101:
    // DEPRECATED. RoleAdmin has the same privileges as RolePublisher.
    // role = rtctokenbuilder.RoleAdmin
    }
    Copy

Update the client

The client does not need any updates as long as the Video Calling Web SDK used in the Web client is v4.8.0 or later. For more information about the SDK versions that support AccessToken2, see SDK compatibility for AccessToken2.

In the index.html file, make the following changes:

<html>
<head>
<title>Token demo</title>
</head>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<body>
<h1>Token demo</h1>
<!-- Remove -->
<!-- <script src="https://download.agora.io/sdk/release/AgoraRTC_N.js"></script>-->
<!-- Upgrade SDK to support AccessToken2.-->
<script src="https://download.agora.io/sdk/release/AgoraRTC_N-4.8.0.js"></script>
<script src="./client.js"></script>
</body>
</html>
Copy

Test the AccessToken2 server

If you are also using other Video SDK related products or services such as Cloud Recording and streaming, Agora recommends you contact the Agora technical support team before upgrading to AccessToken2.

To test the AccessToken2 server, open index.html with a supported browser to perform the following actions:

  • Successfully joining a channel.
  • Renewing a token every 10 seconds.

Voice Calling