Skip to main content

You are viewing Agora Docs forBetaproducts and features. Switch to Docs

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:

    <properties>
    <java.version>11</java.version>
    <spring-boot.version>2.4.3</spring-boot.version>
    </properties>

    <packaging>jar</packaging>

    <dependencyManagement>
    <dependencies>
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-dependencies</artifactId>
    <version>${spring-boot.version}</version>
    <type>pom</type>
    <scope>import</scope>
    </dependency>
    </dependencies>
    </dependencyManagement>

    <dependencies>
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    </dependency>
    <dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.14</version>
    </dependency>
    <dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>30.0-jre</version>
    </dependency>

    <!-- agoraTools -->
    <dependency>
    <groupId>io.agora</groupId>
    <artifactId>authentication</artifactId>
    <version>2.0.0</version>
    </dependency>
    </dependencies>

    <build>
    <plugins>
    <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <version>2.4.1</version>
    <executions>
    <execution>
    <goals>
    <goal>repackage</goal>
    </goals>
    </execution>
    </executions>
    </plugin>
    </plugins>
    </build>
    Copy
  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.

    ## Server port.
    server.port=8090
    ## Fill the App ID of your Agora project.
    appid=
    ## Fill the app certificate of your Agora project.
    appcert=
    ## Set the token validity period (in second).
    expire.second=6000
    ## Fill the App Key of your Agora project.
    appkey=
    ## Set the domain of Agora Chat RESTful APIs.
    domain=
    Copy
    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:

    package com.agora.chat.token;

    import com.google.common.cache.Cache;
    import com.google.common.cache.CacheBuilder;
    import io.agora.chat.ChatTokenBuilder2;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.http.*;
    import org.springframework.util.StringUtils;
    import org.springframework.web.bind.annotation.CrossOrigin;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.client.RestClientException;
    import org.springframework.web.client.RestTemplate;

    import javax.annotation.PostConstruct;
    import java.util.*;
    import java.util.concurrent.TimeUnit;

    @RestController
    @CrossOrigin
    public class AgoraChatTokenController {

    @Value("${appid}")
    private String appid;

    @Value("${appcert}")
    private String appcert;

    @Value("${expire.second}")
    private int expire;

    @Value("${appkey}")
    private String appkey;

    @Value("${domain}")
    private String domain;

    private final RestTemplate restTemplate = new RestTemplate();

    private Cache<String, String> agoraChatAppTokenCache;

    @PostConstruct
    public void init() {
    agoraChatAppTokenCache = CacheBuilder.newBuilder().maximumSize(1).expireAfterWrite(expire, TimeUnit.SECONDS).build();
    }

    /**
    * Gets a token with app privileges.
    *
    * @return app privileges token
    */
    @GetMapping("/chat/app/token")
    public String getAppToken() {

    if (!StringUtils.hasText(appid) || !StringUtils.hasText(appcert)) {
    return "appid or appcert is not empty";
    }

    return getAgoraAppToken();
    }

    /**
    * Gets a token with user privileges.
    *
    * @param chatUserName ChatUserName
    * @return user privileges token
    */
    @GetMapping("/chat/user/{chatUserName}/token")
    public String getChatToken(@PathVariable String chatUserName) {

    if (!StringUtils.hasText(appid) || !StringUtils.hasText(appcert)) {
    return "appid or appcert is not empty";
    }

    if (!StringUtils.hasText(appkey) || !StringUtils.hasText(domain)) {
    return "appkey or domain is not empty";
    }

    if (!appkey.contains("#")) {
    return "appkey is illegal";
    }

    if (!StringUtils.hasText(chatUserName)) {
    return "chatUserName is not empty";
    }

    ChatTokenBuilder2 builder = new ChatTokenBuilder2();

    String chatUserUuid = getChatUserUuid(chatUserName);

    if (chatUserUuid == null) {
    chatUserUuid = registerChatUser(chatUserName);
    }

    return builder.buildUserToken(appid, appcert, chatUserUuid, expire);
    }

    /**
    * Creates a user with the password "123", and gets UUID.
    *
    * @param chatUserName The username of the agora chat user.
    * @return uuid
    */
    private String registerChatUser(String chatUserName) {

    String orgName = appkey.split("#")[0];

    String appName = appkey.split("#")[1];

    String url = "http://" + domain + "/" + orgName + "/" + appName + "/users";

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    headers.setBearerAuth(getAgoraChatAppTokenFromCache());

    Map<String, String> body = new HashMap<>();
    body.put("username", chatUserName);
    body.put("password", "123");

    HttpEntity<Map<String, String>> entity = new HttpEntity<>(body, headers);

    ResponseEntity<Map> response;

    try {
    response = restTemplate.exchange(url, HttpMethod.POST, entity, Map.class);
    } catch (Exception e) {
    throw new RestClientException("register chat user error : " + e.getMessage());
    }

    List<Map<String, Object>> results = (List<Map<String, Object>>) response.getBody().get("entities");

    return (String) results.get(0).get("uuid");
    }

    /**
    * Gets the UUID of the user.
    *
    * @param chatUserName The username of the agora chat user.
    * @return uuid
    */
    private String getChatUserUuid(String chatUserName) {

    String orgName = appkey.split("#")[0];

    String appName = appkey.split("#")[1];

    String url = "http://" + domain + "/" + orgName + "/" + appName + "/users/" + chatUserName;

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    headers.setBearerAuth(getAgoraChatAppTokenFromCache());

    HttpEntity<Map<String, String>> entity = new HttpEntity<>(null, headers);

    ResponseEntity<Map> responseEntity = null;

    try {
    responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, Map.class);
    } catch (Exception e) {
    System.out.println("get chat user error : " + e.getMessage());
    }

    if (responseEntity != null) {

    List<Map<String, Object>> results = (List<Map<String, Object>>) responseEntity.getBody().get("entities");

    return (String) results.get(0).get("uuid");
    }

    return null;
    }

    /**
    * Generate a token with app privileges.
    *
    * @return token
    */
    private String getAgoraAppToken() {
    if (!StringUtils.hasText(appid) || !StringUtils.hasText(appcert)) {
    throw new IllegalArgumentException("appid or appcert is not empty");
    }

    // Use agora App Id and App Cert to generate an Agora app token.
    ChatTokenBuilder2 builder = new ChatTokenBuilder2();
    return builder.buildAppToken(appid, appcert, expire);
    }

    /**
    * Get the token with app privileges from the cache
    *
    * @return token
    */
    private String getAgoraChatAppTokenFromCache() {
    try {
    return agoraChatAppTokenCache.get("agora-chat-app-token", () -> {
    return getAgoraAppToken();
    });
    } catch (Exception e) {
    throw new IllegalArgumentException("Get Agora Chat app token from cache error");
    }
    }

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

    package com.agora.chat.token;

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;

    @SpringBootApplication(scanBasePackages = "com.agora")
    public class AgoraChatTokenStarter {
    public static void main(String[] args) {
    SpringApplication.run(AgoraChatTokenStarter.class, args);
    }
    }
    Copy
  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:

// Generates a token with app privileges. The parameters `appid`, `appcert`, and `expire` refer to App ID, App certificate, and token validity period respectively.
AccessToken2 accessToken = new AccessToken2(appid, appcert, expire);
AccessToken2.Service serviceChat = new AccessToken2.ServiceChat();
serviceChat.addPrivilegeChat(AccessToken2.PrivilegeChat.PRIVILEGE_CHAT_APP, expire);
accessToken.addService(serviceChat);

try {
return accessToken.build();
} catch (Exception e) {
e.printStackTrace();
return "";
}
Copy
  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.

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

    Your app server returns a token like the following example:

    007eJxTYPj3p2Tnb4tznzxfO/0LK5cu/GZmI71PnWPVkbVhP/aniEspMBhbJJqnGKclmVsYJ5kYWBhbJqcapqRZpJmbm5ikGRsnnT12OrGhN5pB97zpVEYGVgZGBiYGEJ+BAQBN0CGG
    Copy
  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.

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

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

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

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

// 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.
AccessToken2 accessToken = new AccessToken2(appid, appcert, expire);
AccessToken2.Service serviceChat = new AccessToken2.ServiceChat(chatUserUuid);

serviceChat.addPrivilegeChat(AccessToken2.PrivilegeChat.PRIVILEGE_CHAT_USER, expire);
accessToken.addService(serviceChat);

try {
return accessToken.build();
} catch (Exception e) {
e.printStackTrace();
return "";
}
Copy

Add the AgoraTools dependency to pom.xml:

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

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:

    const path = require('path');

    module.exports = {
    entry: './index.js',
    mode: 'production',
    output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, './dist'),
    },
    devServer: {
    compress: true,
    port: 9000,
    https: true
    }
    };
    Copy
  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.

    {
    "name": "web",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
    "build": "webpack --config webpack.config.js",
    "start:dev": "webpack serve --open --config webpack.config.js"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "dependencies": {
    "agora-chat": "latest"
    },
    "devDependencies": {
    "webpack": "^5.50.0",
    "webpack-cli": "^4.8.0",
    "webpack-dev-server": "^3.11.2"
    }
    }
    Copy
  5. Create the UI. Replace the code in the index.html file with the following code:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <title>Agora Chat Token demo</title>
    </head>

    <body>
    <h1>Token demo</h1>
    <div class="input-field">
    <label>Username</label>
    <input type="text" placeholder="Username" id="username" />
    </div>
    <div>
    <button type="button" id="login">Login</button>
    </div>
    <div id="log"></div>
    <script src="./dist/bundle.js"></script>
    </body>
    </html>
    Copy
  6. Create the app logic. In index.js, add the following code and replace <Your App Key> with your app key.

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

    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:

      # Use webpack to package the project
      npm run build

      # Use webpack-dev-server to run the project
      npm run start:dev
      Copy

      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

    public String buildUserToken(String appId, String appCertificate, String uuid, int expire) {
    AccessToken2 accessToken = new AccessToken2(appId, appCertificate, expire);
    AccessToken2.Service serviceChat = new AccessToken2.ServiceChat(uuid);
    serviceChat.addPrivilegeChat(AccessToken2.PrivilegeChat.PRIVILEGE_CHAT_USER, expire);
    accessToken.addService(serviceChat);
    try {
    return accessToken.build();
    } catch (Exception e) {
    e.printStackTrace();
    return "";
    }
    }
    Copy
  • Generate a token with app privileges

    public String buildAppToken(String appId, String appCertificate, int expire) {
    AccessToken2 accessToken = new AccessToken2(appId, appCertificate, expire);
    AccessToken2.Service serviceChat = new AccessToken2.ServiceChat();

    serviceChat.addPrivilegeChat(AccessToken2.PrivilegeChat.PRIVILEGE_CHAT_APP, expire);
    accessToken.addService(serviceChat);

    try {
    return accessToken.build();
    } catch (Exception e) {
    e.printStackTrace();
    return "";
    }
    }
    Copy

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