Skip to main content
Android
iOS
Web
Windows
Unity
Flutter
React Native

Secure authentication with tokens

Authentication is the process of validating identities. Agora uses digital tokens to authenticate users and their privileges before they access an Agora service, such as joining an Agora call, or logging in to Agora Chat.

To ensure security in real-time communication, Agora provides tokens for you to authenticate your users. For test purposes, you can generate temporary tokens in Agora Console. See Manage users and generate tokens for details.

However, in the development environment, you need to deploy your own app server to use AgoraTools to generate tokens.

Tokens, generated in your app server, can be used in the following scenarios:

Applicable scenariosUsed TokenToken consists of the followingToken maximum validity period
RESTful API callsToken with app privileges
  • App ID of your Agora Chat project
  • App certificate of your Agora Chat project
  • Token validity period for your Agora Chat project
24 hours
SDK API callsToken with user privileges
  • App ID of your Agora Chat project
  • App certificate of your Agora Chat project
  • Token validity period for your Agora Chat project
  • UUID of the user to be authenticated.
The UUID is a unique internal identifier that Agora Chat generates for a user through User Registration REST APIs.
24 hours

This page introduces how to retrieve tokens from your app server to authenticate your users.

Understand the tech

  • The following diagram shows the process of authenticating users using a token with app privileges.

  • The following diagram shows the process of authenticating users using a token with user privileges.

Prerequisites

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

If you have a firewall implemented in your network environment, Agora provides a firewall whitelist solution for you to access Agora Chat in environments with restricted network access. If you want to use the firewall whitelist solution, submit a ticket and our technical support will provide the target domain and corresponding IP.

Implement the authentication flow

This section shows you how to supply and consume a token used to authenticate a user with Agora Chat.

Deploy an app server to generate tokens

Tokens used in Agora Chat need to be generated in your app server. When the client end sends a request, the app server generate a token accordingly.

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

This sample server is for demonstration purposes only. Do not use it in a production environment.

The following figure shows the API call sequence of generating an Agora Chat token with user privileges: token_generate_user_token

  1. Create a Maven project in IntelliJ, set the name of your project, choose the location to save your project, then click Finish.

  2. In the <Project name>/pom.xml file, add the following dependencies and click Reload project:


    _67
    <properties>
    _67
    <java.version>11</java.version>
    _67
    <spring-boot.version>2.4.3</spring-boot.version>
    _67
    </properties>
    _67
    _67
    <packaging>jar</packaging>
    _67
    _67
    <dependencyManagement>
    _67
    <dependencies>
    _67
    <dependency>
    _67
    <groupId>org.springframework.boot</groupId>
    _67
    <artifactId>spring-boot-dependencies</artifactId>
    _67
    <version>${spring-boot.version}</version>
    _67
    <type>pom</type>
    _67
    <scope>import</scope>
    _67
    </dependency>
    _67
    </dependencies>
    _67
    </dependencyManagement>
    _67
    _67
    <dependencies>
    _67
    <dependency>
    _67
    <groupId>org.springframework.boot</groupId>
    _67
    <artifactId>spring-boot-starter-web</artifactId>
    _67
    </dependency>
    _67
    <dependency>
    _67
    <groupId>org.springframework.boot</groupId>
    _67
    <artifactId>spring-boot-starter</artifactId>
    _67
    </dependency>
    _67
    <dependency>
    _67
    <groupId>org.springframework.boot</groupId>
    _67
    <artifactId>spring-boot-configuration-processor</artifactId>
    _67
    </dependency>
    _67
    <dependency>
    _67
    <groupId>commons-codec</groupId>
    _67
    <artifactId>commons-codec</artifactId>
    _67
    <version>1.14</version>
    _67
    </dependency>
    _67
    <dependency>
    _67
    <groupId>com.google.guava</groupId>
    _67
    <artifactId>guava</artifactId>
    _67
    <version>30.0-jre</version>
    _67
    </dependency>
    _67
    _67
    <!-- agoraTools -->
    _67
    <dependency>
    _67
    <groupId>io.agora</groupId>
    _67
    <artifactId>authentication</artifactId>
    _67
    <version>2.0.0</version>
    _67
    </dependency>
    _67
    </dependencies>
    _67
    _67
    <build>
    _67
    <plugins>
    _67
    <plugin>
    _67
    <groupId>org.springframework.boot</groupId>
    _67
    <artifactId>spring-boot-maven-plugin</artifactId>
    _67
    <version>2.4.1</version>
    _67
    <executions>
    _67
    <execution>
    _67
    <goals>
    _67
    <goal>repackage</goal>
    _67
    </goals>
    _67
    </execution>
    _67
    </executions>
    _67
    </plugin>
    _67
    </plugins>
    _67
    </build>

  3. In <Project name>/src/main/resource, create an application.properties file to store the information for generating tokens and update it with your project information and token validity period. For example, set expire.second as 6000, which means the token is valid for 6000 seconds.

    1. Download the chat and media packages.
    2. In your token server project, create a com.agora.chat.token.io.agora package under <Project name>/src/main/java.
    3. Copy the chat and media packages and paste them under com.agora.chat.token.io.agora. Now the project structure is as following screenshot shows:
    4. Fix the import errors in the chat/ChatTokenBuilder2 and media/AccessToken files.
      • In ChatTokenBuilder2, change package io.agora.chat; to package com.agora.chat.token.io.agora.chat; and change import io.agora.media.AccessToken2; to import com.agora.chat.token.io.agora.media.AccessToken2;.
      • In all files of the com.agora.chat.token.io.agora.media package, change package io.agora.media; to package com.agora.chat.token.io.agora.media;.
      • In AccessToken, change import static io.agora.media.Utils.crc32; to import static com.agora.chat.token.io.agora.media.Utils.crc32;.
  4. In <Project name>/src/main/resource, create an application.properties file to store the information for generating tokens and update it with your project information and token validity period. For example, set expire.second as 6000, which means the token is valid for 6000 seconds.


    _12
    ## Server port.
    _12
    server.port=8090
    _12
    ## Fill the App ID of your Agora project.
    _12
    appid=
    _12
    ## Fill the app certificate of your Agora project.
    _12
    appcert=
    _12
    ## Set the token validity period (in second).
    _12
    expire.second=6000
    _12
    ## Fill the App Key of your Agora project.
    _12
    appkey=
    _12
    ## Set the domain of Agora Chat RESTful APIs.
    _12
    domain=

    To get the app key and the RESTful API domain, refer to Get the information of the Agora Chat project.
  5. In the com.agora.chat.token package, create a Java class named AgoraChatTokenController with the following content:


    _205
    package com.agora.chat.token;
    _205
    _205
    import com.google.common.cache.Cache;
    _205
    import com.google.common.cache.CacheBuilder;
    _205
    import io.agora.chat.ChatTokenBuilder2;
    _205
    import org.springframework.beans.factory.annotation.Value;
    _205
    import org.springframework.http.*;
    _205
    import org.springframework.util.StringUtils;
    _205
    import org.springframework.web.bind.annotation.CrossOrigin;
    _205
    import org.springframework.web.bind.annotation.GetMapping;
    _205
    import org.springframework.web.bind.annotation.PathVariable;
    _205
    import org.springframework.web.bind.annotation.RestController;
    _205
    import org.springframework.web.client.RestClientException;
    _205
    import org.springframework.web.client.RestTemplate;
    _205
    _205
    import javax.annotation.PostConstruct;
    _205
    import java.util.*;
    _205
    import java.util.concurrent.TimeUnit;
    _205
    _205
    @RestController
    _205
    @CrossOrigin
    _205
    public class AgoraChatTokenController {
    _205
    _205
    @Value("${appid}")
    _205
    private String appid;
    _205
    _205
    @Value("${appcert}")
    _205
    private String appcert;
    _205
    _205
    @Value("${expire.second}")
    _205
    private int expire;
    _205
    _205
    @Value("${appkey}")
    _205
    private String appkey;
    _205
    _205
    @Value("${domain}")
    _205
    private String domain;
    _205
    _205
    private final RestTemplate restTemplate = new RestTemplate();
    _205
    _205
    private Cache<String, String> agoraChatAppTokenCache;
    _205
    _205
    @PostConstruct
    _205
    public void init() {
    _205
    agoraChatAppTokenCache = CacheBuilder.newBuilder().maximumSize(1).expireAfterWrite(expire, TimeUnit.SECONDS).build();
    _205
    }
    _205
    _205
    /**
    _205
    * Gets a token with app privileges.
    _205
    *
    _205
    * @return app privileges token
    _205
    */
    _205
    @GetMapping("/chat/app/token")
    _205
    public String getAppToken() {
    _205
    _205
    if (!StringUtils.hasText(appid) || !StringUtils.hasText(appcert)) {
    _205
    return "appid or appcert is not empty";
    _205
    }
    _205
    _205
    return getAgoraAppToken();
    _205
    }
    _205
    _205
    /**
    _205
    * Gets a token with user privileges.
    _205
    *
    _205
    * @param chatUserName ChatUserName
    _205
    * @return user privileges token
    _205
    */
    _205
    @GetMapping("/chat/user/{chatUserName}/token")
    _205
    public String getChatToken(@PathVariable String chatUserName) {
    _205
    _205
    if (!StringUtils.hasText(appid) || !StringUtils.hasText(appcert)) {
    _205
    return "appid or appcert is not empty";
    _205
    }
    _205
    _205
    if (!StringUtils.hasText(appkey) || !StringUtils.hasText(domain)) {
    _205
    return "appkey or domain is not empty";
    _205
    }
    _205
    _205
    if (!appkey.contains("#")) {
    _205
    return "appkey is illegal";
    _205
    }
    _205
    _205
    if (!StringUtils.hasText(chatUserName)) {
    _205
    return "chatUserName is not empty";
    _205
    }
    _205
    _205
    ChatTokenBuilder2 builder = new ChatTokenBuilder2();
    _205
    _205
    String chatUserUuid = getChatUserUuid(chatUserName);
    _205
    _205
    if (chatUserUuid == null) {
    _205
    chatUserUuid = registerChatUser(chatUserName);
    _205
    }
    _205
    _205
    return builder.buildUserToken(appid, appcert, chatUserUuid, expire);
    _205
    }
    _205
    _205
    /**
    _205
    * Creates a user with the password "123", and gets UUID.
    _205
    *
    _205
    * @param chatUserName The username of the agora chat user.
    _205
    * @return uuid
    _205
    */
    _205
    private String registerChatUser(String chatUserName) {
    _205
    _205
    String orgName = appkey.split("#")[0];
    _205
    _205
    String appName = appkey.split("#")[1];
    _205
    _205
    String url = "http://" + domain + "/" + orgName + "/" + appName + "/users";
    _205
    _205
    HttpHeaders headers = new HttpHeaders();
    _205
    headers.setContentType(MediaType.APPLICATION_JSON);
    _205
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    _205
    headers.setBearerAuth(getAgoraChatAppTokenFromCache());
    _205
    _205
    Map<String, String> body = new HashMap<>();
    _205
    body.put("username", chatUserName);
    _205
    body.put("password", "123");
    _205
    _205
    HttpEntity<Map<String, String>> entity = new HttpEntity<>(body, headers);
    _205
    _205
    ResponseEntity<Map> response;
    _205
    _205
    try {
    _205
    response = restTemplate.exchange(url, HttpMethod.POST, entity, Map.class);
    _205
    } catch (Exception e) {
    _205
    throw new RestClientException("register chat user error : " + e.getMessage());
    _205
    }
    _205
    _205
    List<Map<String, Object>> results = (List<Map<String, Object>>) response.getBody().get("entities");
    _205
    _205
    return (String) results.get(0).get("uuid");
    _205
    }
    _205
    _205
    /**
    _205
    * Gets the UUID of the user.
    _205
    *
    _205
    * @param chatUserName The username of the agora chat user.
    _205
    * @return uuid
    _205
    */
    _205
    private String getChatUserUuid(String chatUserName) {
    _205
    _205
    String orgName = appkey.split("#")[0];
    _205
    _205
    String appName = appkey.split("#")[1];
    _205
    _205
    String url = "http://" + domain + "/" + orgName + "/" + appName + "/users/" + chatUserName;
    _205
    _205
    HttpHeaders headers = new HttpHeaders();
    _205
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    _205
    headers.setBearerAuth(getAgoraChatAppTokenFromCache());
    _205
    _205
    HttpEntity<Map<String, String>> entity = new HttpEntity<>(null, headers);
    _205
    _205
    ResponseEntity<Map> responseEntity = null;
    _205
    _205
    try {
    _205
    responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, Map.class);
    _205
    } catch (Exception e) {
    _205
    System.out.println("get chat user error : " + e.getMessage());
    _205
    }
    _205
    _205
    if (responseEntity != null) {
    _205
    _205
    List<Map<String, Object>> results = (List<Map<String, Object>>) responseEntity.getBody().get("entities");
    _205
    _205
    return (String) results.get(0).get("uuid");
    _205
    }
    _205
    _205
    return null;
    _205
    }
    _205
    _205
    /**
    _205
    * Generate a token with app privileges.
    _205
    *
    _205
    * @return token
    _205
    */
    _205
    private String getAgoraAppToken() {
    _205
    if (!StringUtils.hasText(appid) || !StringUtils.hasText(appcert)) {
    _205
    throw new IllegalArgumentException("appid or appcert is not empty");
    _205
    }
    _205
    _205
    // Use agora App Id and App Cert to generate an Agora app token.
    _205
    ChatTokenBuilder2 builder = new ChatTokenBuilder2();
    _205
    return builder.buildAppToken(appid, appcert, expire);
    _205
    }
    _205
    _205
    /**
    _205
    * Get the token with app privileges from the cache
    _205
    *
    _205
    * @return token
    _205
    */
    _205
    private String getAgoraChatAppTokenFromCache() {
    _205
    try {
    _205
    return agoraChatAppTokenCache.get("agora-chat-app-token", () -> {
    _205
    return getAgoraAppToken();
    _205
    });
    _205
    } catch (Exception e) {
    _205
    throw new IllegalArgumentException("Get Agora Chat app token from cache error");
    _205
    }
    _205
    }
    _205
    _205
    }

  6. In the com.agora.chat.token package, create a Java class named AgoraChatTokenStarter with the following content:


    _11
    package com.agora.chat.token;
    _11
    _11
    import org.springframework.boot.SpringApplication;
    _11
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    _11
    _11
    @SpringBootApplication(scanBasePackages = "com.agora")
    _11
    public class AgoraChatTokenStarter {
    _11
    public static void main(String[] args) {
    _11
    SpringApplication.run(AgoraChatTokenStarter.class, args);
    _11
    }
    _11
    }

  7. To start the server, click the green triangle button, and select Debug "AgoraChatTokenStarter...".

Call Agora Chat RESTful APIs with tokens

This section introduces how to get a token with app privileges and call the Agora Chat RESTful APIs to create a user in your app.

The core methods for generating a token with app privileges in the app server are as follows:


_12
// Generates a token with app privileges. The parameters `appid`, `appcert`, and `expire` refer to App ID, App certificate, and token validity period respectively.
_12
AccessToken2 accessToken = new AccessToken2(appid, appcert, expire);
_12
AccessToken2.Service serviceChat = new AccessToken2.ServiceChat();
_12
serviceChat.addPrivilegeChat(AccessToken2.PrivilegeChat.PRIVILEGE_CHAT_APP, expire);
_12
accessToken.addService(serviceChat);
_12
_12
try {
_12
return accessToken.build();
_12
} catch (Exception e) {
_12
e.printStackTrace();
_12
return "";
_12
}

  1. Get a token for Agora Chat. In the terminal, use the following curl command to send a GET request to your app server to get a token.


    _1
    curl http://localhost:8090/chat/app/token

    Your app server returns a token like the following example:


    _1
    007eJxTYPj3p2Tnb4tznzxfO/0LK5cu/GZmI71PnWPVkbVhP/aniEspMBhbJJqnGKclmVsYJ5kYWBhbJqcapqRZpJmbm5ikGRsnnT12OrGhN5pB97zpVEYGVgZGBiYGEJ+BAQBN0CGG

  2. Call the Agora Chat RESTful APIs to create a new user. In the terminal, use the following curl command to send the request of creating a new user to the Agora Chat server.


    _7
    curl -X POST -H "Authorization: Bearer <YourAgoraAppToken>" -i "https://XXXX/XXXX/XXXX/users" -d '[
    _7
    {
    _7
    "username": "user1",
    _7
    "password": "123",
    _7
    "nickname": "testuser"
    _7
    }
    _7
    ]'

    The response parameters contains the information of the new user as shown in the following example:


    _21
    {
    _21
    "action": "post",
    _21
    "application": "8be024f0-e978-11e8-b697-5d598d5f8402",
    _21
    "path": "/users",
    _21
    "uri": "https://a1.agora.com/XXXX/XXXX/users",
    _21
    "entities": [
    _21
    {
    _21
    "uuid": "0ffe2d80-ed76-11e8-8d66-279e3e1c214b",
    _21
    "type": "user",
    _21
    "created": 1542795196504,
    _21
    "modified": 1542795196504,
    _21
    "username": "user1",
    _21
    "activated": true,
    _21
    "nickname": "testuser"
    _21
    }
    _21
    ],
    _21
    "timestamp": 1542795196515,
    _21
    "duration": 0,
    _21
    "organization": "XXXX",
    _21
    "applicationName": "XXXX"
    _21
    }

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.

The core methods of generating a token with user privileges in the app server are as follows:


_13
// Generates a token with app privileges. The parameters `appid`, `appcert`, `expire` and `chatUserUuid` refer to App ID, App certificate, token validity period and UUID of the Agora Chat user respectively.
_13
AccessToken2 accessToken = new AccessToken2(appid, appcert, expire);
_13
AccessToken2.Service serviceChat = new AccessToken2.ServiceChat(chatUserUuid);
_13
_13
serviceChat.addPrivilegeChat(AccessToken2.PrivilegeChat.PRIVILEGE_CHAT_USER, expire);
_13
accessToken.addService(serviceChat);
_13
_13
try {
_13
return accessToken.build();
_13
} catch (Exception e) {
_13
e.printStackTrace();
_13
return "";
_13
}

Add the AgoraTools dependency to pom.xml:


_5
<dependency>
_5
<groupId>io.agora</groupId>
_5
<artifactId>authentication</artifactId>
_5
<version>2.0.0</version>
_5
</dependency>

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.

To implement the Web client, do the following:

  1. Create a project structure for an Agora Chat Web app. In the project root folder, create the following files:

    • index.html: The user interface.
    • index.js: The app logic.
    • webpack.config.js: The webpack configuration.
  2. To configure webpack, copy the following code into webpack.config.js:


    _15
    const path = require('path');
    _15
    _15
    module.exports = {
    _15
    entry: './index.js',
    _15
    mode: 'production',
    _15
    output: {
    _15
    filename: 'bundle.js',
    _15
    path: path.resolve(__dirname, './dist'),
    _15
    },
    _15
    devServer: {
    _15
    compress: true,
    _15
    port: 9000,
    _15
    https: true
    _15
    }
    _15
    };

  3. Set up the npm package for your Web app. In the terminal, navigate to the project root directory and run npm init. This creates a package.json file.

  4. Configure the dependencies for your project. Copy the following code into the package.json file.


    _21
    {
    _21
    "name": "web",
    _21
    "version": "1.0.0",
    _21
    "description": "",
    _21
    "main": "index.js",
    _21
    "scripts": {
    _21
    "build": "webpack --config webpack.config.js",
    _21
    "start:dev": "webpack serve --open --config webpack.config.js"
    _21
    },
    _21
    "keywords": [],
    _21
    "author": "",
    _21
    "license": "ISC",
    _21
    "dependencies": {
    _21
    "agora-chat": "latest"
    _21
    },
    _21
    "devDependencies": {
    _21
    "webpack": "^5.50.0",
    _21
    "webpack-cli": "^4.8.0",
    _21
    "webpack-dev-server": "^3.11.2"
    _21
    }
    _21
    }

  5. Create the UI. Replace the code in the index.html file with the following code:


    _19
    <!DOCTYPE html>
    _19
    <html lang="en">
    _19
    <head>
    _19
    <title>Agora Chat Token demo</title>
    _19
    </head>
    _19
    _19
    <body>
    _19
    <h1>Token demo</h1>
    _19
    <div class="input-field">
    _19
    <label>Username</label>
    _19
    <input type="text" placeholder="Username" id="username" />
    _19
    </div>
    _19
    <div>
    _19
    <button type="button" id="login">Login</button>
    _19
    </div>
    _19
    <div id="log"></div>
    _19
    <script src="./dist/bundle.js"></script>
    _19
    </body>
    _19
    </html>

  6. Create the app logic. In index.js, add the following code and replace <Your App Key> with your app key.


    _65
    import WebIM from "agora-chat-sdk";
    _65
    WebIM.conn = new WebIM.connection({
    _65
    appKey: "<Your App Key>",
    _65
    });
    _65
    // Logs in to Agora Chat.
    _65
    let username;
    _65
    document.getElementById("login").onclick = function () {
    _65
    username = document.getElementById("username").value.toString();
    _65
    // Use the user name to gets a token with user privileges.
    _65
    fetch(`http://localhost:8090/chat/user/${username}/token`)
    _65
    .then((res) => res.text())
    _65
    .then((token) => {
    _65
    // Logs in to Agora Chat using the user name and the token with user privileges.
    _65
    WebIM.conn.open({
    _65
    user: username,
    _65
    agoraToken: token,
    _65
    });
    _65
    });
    _65
    };
    _65
    // Adds an event handler.
    _65
    WebIM.conn.addEventHandler("AUTHHANDLER", {
    _65
    // The event handler for successfully connecting to the server.
    _65
    onConnected: () => {
    _65
    document
    _65
    .getElementById("log")
    _65
    .appendChild(document.createElement("div"))
    _65
    .append("Connect success !");
    _65
    },
    _65
    // The event handler for receiving a text message.
    _65
    onTextMessage: (message) => {
    _65
    console.log(message);
    _65
    document
    _65
    .getElementById("log")
    _65
    .appendChild(document.createElement("div"))
    _65
    .append("Message from: " + message.from + " Message: " + message.data);
    _65
    },
    _65
    // The event handler for the token about to expire.
    _65
    onTokenWillExpire: (params) => {
    _65
    document
    _65
    .getElementById("log")
    _65
    .appendChild(document.createElement("div"))
    _65
    .append("Token is about to expire");
    _65
    refreshToken(username);
    _65
    },
    _65
    // The event handler for the token already expired.
    _65
    onTokenExpired: (params) => {
    _65
    document
    _65
    .getElementById("log")
    _65
    .appendChild(document.createElement("div"))
    _65
    .append("The token has expired");
    _65
    refreshToken(username);
    _65
    },
    _65
    onError: (error) => {
    _65
    console.log("on error", error);
    _65
    },
    _65
    });
    _65
    // Renews the token.
    _65
    function refreshToken(username) {
    _65
    fetch(`http://localhost:8090/chat/user/${username}/token`)
    _65
    .then((res) => res.text())
    _65
    .then((token) => {
    _65
    WebIM.conn.renewToken(token);
    _65
    }
    _65
    );
    _65
    }

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

    • Call open to log in to the Agora Chat system with token and username. You must use the username that is used to register the user and get the UUID.
    • Fetch a new token from the app server and call renewToken to update the token of the SDK when the token is about to expire and when the token expires. Agora recommends that you regularly (such as every hour) generate a token from the app server and call renewToken to update the token of the SDK to ensure that the token is always valid.
  7. To build and run your project, do the following:

    1. To install the dependencies, run npm install.

    2. To build and run the project using webpack, run the following commands:


      _5
      # Use webpack to package the project
      _5
      npm run build
      _5
      _5
      # Use webpack-dev-server to run the project
      _5
      npm run start:dev

      The index.html page opens in your browser.

    3. Input a user name and click the login button. Open the browser console, and you can see the web client performs the following actions:

      • Generates a token with user privileges.
      • Connects to the Agora Chat system.
      • Renews a token when it is about to expire.

Reference

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

Token generator libraries

Agora Chat 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.

API reference

This section introduces the method to generate a token for Agora Chat. Take Java as an example:

  • Generate a token with user privileges


    _12
    public String buildUserToken(String appId, String appCertificate, String uuid, int expire) {
    _12
    AccessToken2 accessToken = new AccessToken2(appId, appCertificate, expire);
    _12
    AccessToken2.Service serviceChat = new AccessToken2.ServiceChat(uuid);
    _12
    serviceChat.addPrivilegeChat(AccessToken2.PrivilegeChat.PRIVILEGE_CHAT_USER, expire);
    _12
    accessToken.addService(serviceChat);
    _12
    try {
    _12
    return accessToken.build();
    _12
    } catch (Exception e) {
    _12
    e.printStackTrace();
    _12
    return "";
    _12
    }
    _12
    }

  • Generate a token with app privileges


    _14
    public String buildAppToken(String appId, String appCertificate, int expire) {
    _14
    AccessToken2 accessToken = new AccessToken2(appId, appCertificate, expire);
    _14
    AccessToken2.Service serviceChat = new AccessToken2.ServiceChat();
    _14
    _14
    serviceChat.addPrivilegeChat(AccessToken2.PrivilegeChat.PRIVILEGE_CHAT_APP, expire);
    _14
    accessToken.addService(serviceChat);
    _14
    _14
    try {
    _14
    return accessToken.build();
    _14
    } catch (Exception e) {
    _14
    e.printStackTrace();
    _14
    return "";
    _14
    }
    _14
    }

Token expiration

A token for Agora Chat is valid for a maximum of 24 hours.

When a token is about to expire or has expired, the Chat SDK triggers the onTokenWillExpire callback or the onTokenExpired callback. You need to take the following actions in your own app logic:

  • Tag the type of privilege that is about to expire or has expired in your app logic.
  • The app fetches a new token from the app server.
  • The SDK calls renewToken to renew the token.

Reconnection upon token expiration

Automatic reconnection upon token expiration can ensure that the Agora Chat service of end users remains connected when the application is running in the background, and does not need to log in again when re-entering the application. The implementation process is as follows:

  1. Deploy an app server to generate tokens and provide an API for retrieving tokens.
  2. Implement monitoring for token expiration on your app. When the token expires, your app needs to obtain a new token via the token retrieval API, and logs in to the Agora server again.

Tokens for Agora RTC products

If you use Agora Chat together with the Agora RTC SDK, Agora recommends you upgrade to AccessToken 2.

vundefined