Skip to main content

Generate an app token

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

To securely connect to Chat, you use the following token types:

  • User token: User level access to Chat from your app using Chat SDK. User tokens are used to authenticate users when they log in to your Chat application. For details, see Implement an Agora user token server for Chat.
  • App token: Admin level access to Chat using the REST API. App tokens grant admin privileges for the app developer to manage the Chat applications, for example, creating and deleting users.

You use Chat app tokens to make authenticated REST calls to Chat. To obtain a Chat app token, you retrieve an Agora app token from your app token server and convert it using the Agora app token obtained to a Chat app token.

Understand the tech

The following figure shows the authentication workflow for Chat REST API:

1640139728606

a Chat app token is valid for a maximum of 24 hours. When you call Chat REST APIs, the Chat server reads the information stored in the token and uses it for authentication. a Chat app token contains the following information:

  • The App ID of your Agora project
  • The App Certificate of your Agora project
  • The valid duration of the token

Preprequisites

If your network environment has a firewall, Agora provides firewall whitelists so that you can use Chat with restricted network access. You can contact support@agora.io for more information about the firewall whitelists.

Implement the authentication flow

This section shows how to implement authentication with a Chat app token step by step.

Create an app token server

Token generators create the tokens requested by your app client to enable secure access to Chat. To serve these tokens you create an app token server.

The following example shows how to build and run an app 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.

  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 <Project name>/pom.xml , add the following dependencies and then reload the Maven project:


    _55
    <properties>
    _55
    <java.version>1.8</java.version>
    _55
    <spring-boot.version>2.4.3</spring-boot.version>
    _55
    </properties>
    _55
    _55
    <packaging>jar</packaging>
    _55
    _55
    <dependencyManagement>
    _55
    <dependencies>
    _55
    <dependency>
    _55
    <groupId>org.springframework.boot</groupId>
    _55
    <artifactId>spring-boot-dependencies</artifactId>
    _55
    <version>${spring-boot.version}</version>
    _55
    <type>pom</type>
    _55
    <scope>import</scope>
    _55
    </dependency>
    _55
    </dependencies>
    _55
    </dependencyManagement>
    _55
    _55
    <dependencies>
    _55
    <dependency>
    _55
    <groupId>org.springframework.boot</groupId>
    _55
    <artifactId>spring-boot-starter-web</artifactId>
    _55
    </dependency>
    _55
    <dependency>
    _55
    <groupId>org.springframework.boot</groupId>
    _55
    <artifactId>spring-boot-starter</artifactId>
    _55
    </dependency>
    _55
    <dependency>
    _55
    <groupId>org.springframework.boot</groupId>
    _55
    <artifactId>spring-boot-configuration-processor</artifactId>
    _55
    </dependency>
    _55
    <dependency>
    _55
    <groupId>commons-codec</groupId>
    _55
    <artifactId>commons-codec</artifactId>
    _55
    <version>1.14</version>
    _55
    </dependency>
    _55
    </dependencies>
    _55
    _55
    <build>
    _55
    <plugins>
    _55
    <plugin>
    _55
    <groupId>org.springframework.boot</groupId>
    _55
    <artifactId>spring-boot-maven-plugin</artifactId>
    _55
    <version>2.4.1</version>
    _55
    <executions>
    _55
    <execution>
    _55
    <goals>
    _55
    <goal>repackage</goal>
    _55
    </goals>
    _55
    </execution>
    _55
    </executions>
    _55
    </plugin>
    _55
    </plugins>
    _55
    </build>

  3. Import the token builders provided by Agora to this project.

    1. Download the chat and media packages.
    2. In the 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 under com.agora.chat.token.io.agora. The following figure shows the project structure:

    1638864182234

    1. Fix the import errors in chat/ChatTokenBuilder2 and media/AccessToken.

      • In ChatTokenBuilder2, the import should be import com.agora.chat.token.io.agora.media.AccessToken2.

      • In AccessToken, the import should be as follows:


        _5
        import java.io.ByteArrayOutputStream;
        _5
        import java.io.IOException;
        _5
        import java.util.TreeMap;
        _5
        _5
        import static com.agora.chat.token.io.agora.media.Utils.crc32;

  4. In <Project name>/src/main/resource, create a application.properties file. You need to update the properties with the value for your Chat project and set the validity period of the Agora app token you request, for example, expire.second=6000.

    Note: The validity period of a Chat app token is subject to that of the Agora app token generated by your token server.

    For example, if you set the validity period of the Agora app token as 10,000 seconds, and you use this token to convert and obtain a Chat app token after 100 seconds, the Chat app token is to be expired after 9,900 seconds.


    _10
    ## server port
    _10
    server.port=8090
    _10
    ## Fill in the App ID of your Agora project
    _10
    appid=
    _10
    ## Fill in the app certificate of your Agora project
    _10
    appcert=
    _10
    ## Set the valid period (in seconds) for the Agora app token
    _10
    expire.second=
    _10
    ## domain
    _10
    domain=

    For details on how to get the REST API domain, see Enable and Configure Chat.

  5. In com.agora.chat.token, create a file named AgoraChatTokenController.java and copy the following codes into the file:


    _38
    package com.agora.chat.token;
    _38
    _38
    import com.agora.chat.token.io.agora.chat.ChatTokenBuilder2;
    _38
    import org.springframework.beans.factory.annotation.Value;
    _38
    import org.springframework.util.StringUtils;
    _38
    import org.springframework.web.bind.annotation.GetMapping;
    _38
    import org.springframework.web.bind.annotation.PathVariable;
    _38
    import org.springframework.web.bind.annotation.RestController;
    _38
    _38
    @RestController
    _38
    public class AgoraChatTokenController {
    _38
    _38
    @Value("${appid}")
    _38
    private String appid;
    _38
    _38
    @Value("${appcert}")
    _38
    private String appcert;
    _38
    _38
    @Value("${expire.second}")
    _38
    private int expire;
    _38
    _38
    /**
    _38
    *
    _38
    * Apply for an App Token
    _38
    * @return token
    _38
    */
    _38
    @GetMapping("/chat/app/token")
    _38
    public String getAppToken() {
    _38
    if (!StringUtils.hasText(appid) || !StringUtils.hasText(appcert)) {
    _38
    return "appid or appcert is not empty";
    _38
    }
    _38
    _38
    ChatTokenBuilder2 builder = new ChatTokenBuilder2();
    _38
    _38
    // Generate an App Token.
    _38
    return builder.buildAppToken(appid, appcert, expire);
    _38
    }
    _38
    }

  6. In com.agora.chat.token , create a Java class named AgoraChatTokenStarter and copy the following codes into the file:


    _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...".

    1638868741690

  8. Now you have created an Agora app token server on your local machine. The server returns an Agora app token on GET requests. To test this, paste http://localhost:8090/chat/app/token in your broswer.

    You see an Agora app token that resembles:

    1638869051945

Call the Chat REST APIs with a Chat app token

This section shows how to create a new user in your Chat using an authenticated call to Chat REST API. To do this you:

  1. Retrieve an Agora app token and convert it to a Chat app token. For example:

    i. In the terminal, use curl to make a GET request to your Agora app token server:


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

    The return parameters contain the Agora app token. For example:


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

  2. Add the Agora app token returned previously as the Authorization: Bear parameter and retrieve a Chat app token:


    _1
    curl -X POST -H 'Content-Type: application/json' -H 'Authorization: Bearer 007eJxTYPj3p2Tnb4tznzxfO/0LK5cu/GZmI71PnWPVkbVhP/aniEspMBhbJJqnGKclmVsYJ5kYWBhbJqcapqRZpJmbm5ikGRsnnT12OrGhN5pB97zpVEYGVgZGBiYGEJ+BAQBN0CGG' -d '{"grant_type":"agora"}' 'http://a41.chat.agora.io/41434878/504205/token'

    The return parameters contain the Chat app token and the timestamp (ms) when the token expires in a JSON object. For example:


    _4
    {
    _4
    "access_token": "YWMtocXMjBEEQhmBqj-1iqWUywAAAAAAAAAAAAAAAAAAAAH_Z4gybPJPQ4EwWKw4y2wVAgMAAAF7D4Ab0QBPGgD6xFOaPCHEVIzBMQAtlGlZ3wQF2Ju68ZHglAxaaFRPRg==",
    _4
    "expire_timestamp": 1628148692771
    _4
    }

  3. Use the Chat app token returned to call the Chat REST API to create a new user:

    i. In terminal, use curl to make a POST request to the Chat server. For example:


    _8
    # Replace <YourAppToken> with the Chat app token you received.
    _8
    curl -X POST -H "Authorization: Bearer <YourAppToken>" -i "https://XXXX/XXXX/XXXX/users" -d '[
    _8
    {
    _8
    "username": "user1",
    _8
    "password": "123",
    _8
    "nickname": "testuser"
    _8
    }
    _8
    ]'

    The return parameters contain the information about the user you just created. For 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
    }

Reference

This section provides additional information about Chat app tokens for your reference.

Request path

The following parameters are required when you send a request for a Chat app token:

ParameterData typeRequired/OptionalDescription
org_nameStringRequiredThe unique identification that the Chat assigns to each customer developing with Chat.
app_nameStringRequiredThe name that the Chat assigns to each app.
tokenStringRequiredThe Agora app token.

Request headers

To convert an Agora app token to a Chat app token, you need to pass in the following parameters in the request header:

ParameterData typeRequired/OptionalDescription
Content-TypeStringRequiredapplication/json
AuthorizationStringRequiredBearer AgoraappToken

Request body

ParameterData typeRequired/OptionalValue
grant_typeStringRequiredagora

Response body

ParameterData typeValue
access_tokenStringThe Chat app token.
expires_inNumberThe valid duration (in seconds) of the token.

Example

Request Example


_1
curl -X POST -H 'Content-Type: application/json' http://<domain>/<org_name>/<app_name>/token -H 'Authorization: Bearer <agora_app_token>' -d '{"grant_type" : "agora"}'

Response Example


_5
{
_5
"access_token": "YWMte2XXXXAAAAAAAAAAAAAAFcaJRiIRZNB6tqNQUcXXXXXXLAAAARmt4MVNn5VYK7z7hP9SbgdqhlVNBPGnYAeGjlt3n80Y_A==",
_5
"expires_in": 281,
_5
"expire_timestamp": 1657015153000
_5
}

Status codes

The possible response status codes are listed below:

Response status codeDescription
200The request is successful, and the server returns the requested Chat app token and the timestamp when the token expires.
5xxThe request fails probably because the API to convert an Agora app token to a Chat app token might be rate-limited, or an error occur during the process.

Other Considerations

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

Page Content