Skip to main content
Android
iOS
Web
Electron

Secure authentication with tokens

Authentication is the act of validating the identity of each user before they access your system. Agora uses digital tokens to authenticate users and their privileges before they access an Agora service, for example, join a classroom.

In order to provide a better authentication experience and security guarantee, on August 18, 2022, Agora launched a new version of the token, AccessToken2. We recommend using AccessToken2, which is compatible with AccessToken.

This page explains how to use AccessToken2 to deploy a token generator on the server and use token authentication on the client, as well as providing reference information.

Understand the tech

The following figure shows the steps in the authentication flow:

FCR authentication flow

An Agora token is a dynamic key generated on your app server that is valid for 24 hours or less. When your users log in to Flexible Classroom from your app client, the 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 user ID

  • The Unix timestamp for when the token expires

Prerequisites

Note
This page provides an example procedure using Go. You can use another language or platform for the same purpose.

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

Implement the authentication flow

This section shows you how to use a token generator to generate tokens and authenticate users.

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 for AccessToken2

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.

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


    _94
    package main
    _94
    _94
    import (
    _94
    educationtokenbuilder "github.com/AgoraIO/Tools/DynamicKey/AgoraDynamicKey/go/src/educationtokenbuilder"
    _94
    "fmt"
    _94
    "log"
    _94
    "net/http"
    _94
    "time"
    _94
    "encoding/json"
    _94
    "errors"
    _94
    "strconv"
    _94
    )
    _94
    _94
    type education_token_struct struct {
    _94
    roomUuid string `json:"roomUuid"`
    _94
    userUuid string `json:"userUuid"`
    _94
    role int `json:"role"`
    _94
    }
    _94
    _94
    var educationToken string
    _94
    _94
    func generateEducationToken(roomUuid string, userUuid string, role int) {
    _94
    // Replace "Your_App_ID" with your app ID
    _94
    appID := "Your_App_ID"
    _94
    // Replace "Your_Certificate" with your app certificate
    _94
    appCertificate := "Your_Certificate"
    _94
    expire := uint32(3600)
    _94
    _94
    result, err := educationtokenbuilder.BuildRoomUserToken(appID, appCertificate, roomUuid, userUuid, role, expire)
    _94
    _94
    if err != nil {
    _94
    fmt.Println(err)
    _94
    } else {
    _94
    fmt.Printf("EducationToken: %s\n", result)
    _94
    educationToken = result
    _94
    }
    _94
    }
    _94
    _94
    func educationTokenHandler(w http.ResponseWriter, r *http.Request) {
    _94
    w.Header().Set("Content-Type", "application/json;charset=UTF-8")
    _94
    w.Header().Set("Access-Control-Allow-Origin", "*")
    _94
    w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS");
    _94
    w.Header().Set("Access-Control-Allow-Headers", "*");
    _94
    _94
    if r.Method == "OPTIONS" {
    _94
    w.WriteHeader(http.StatusOK)
    _94
    return
    _94
    }
    _94
    _94
    if r.Method != "POST" && r.Method != "OPTIONS" {
    _94
    http.Error(w, "Unsupported method. Please check.", http.StatusNotFound)
    _94
    return
    _94
    }
    _94
    _94
    var t_education_str education_token_struct
    _94
    var unmarshalErr *json.UnmarshalTypeError
    _94
    str_decoder := json.NewDecoder(r.Body)
    _94
    education_err := str_decoder.Decode(&t_education_str)
    _94
    _94
    if (education_err != nil) {
    _94
    if errors.As(education_err, &unmarshalErr) {
    _94
    errorResponse(w, "Bad request. Please check your params.", http.StatusBadRequest)
    _94
    } else {
    _94
    errorResponse(w, "Bad request.", http.StatusBadRequest)
    _94
    }
    _94
    return
    _94
    }
    _94
    _94
    generateRtmToken(t_education_str.roomUuid,t_education_str.userUuid,t_education_str.role)
    _94
    errorResponse(w, educationToken, http.StatusOK)
    _94
    log.Println(w, r)
    _94
    }
    _94
    _94
    func errorResponse(w http.ResponseWriter, message string, httpStatusCode int) {
    _94
    w.Header().Set("Content-Type", "application/json")
    _94
    w.Header().Set("Access-Control-Allow-Origin", "*")
    _94
    w.WriteHeader(httpStatusCode)
    _94
    resp := make(map[string]string)
    _94
    resp["token"] = message
    _94
    resp["code"] = strconv.Itoa(httpStatusCode)
    _94
    jsonResp, _ := json.Marshal(resp)
    _94
    w.Write(jsonResp)
    _94
    }
    _94
    _94
    func main() {
    _94
    // Handle routing
    _94
    http.HandleFunc("/fetch_education_token", educationTokenHandler)
    _94
    _94
    fmt.Printf("Starting server at port 8082\n")
    _94
    _94
    if err := http.ListenAndServe(":8082", nil); err != nil {
    _94
    log.Fatal(err)
    _94
    }
    _94
    }

  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:


    _1
    $ go mod init sampleServer

  3. Get dependencies by running the following command:


    _1
    $ go get

  4. Start the server by running the following command:


    _1
    $ go run server.go

Use AccessToken2 for authentication

This section uses the Web client as an example to show how to use a token for client-side user authentication. The following reference code comes from the Flexible Classroom web source code.

  1. Initiate a token request to the server integrated with the Agora token generator:


    _5
    const { token, appId } = await roomApi.getCredentialNoAuth({
    _5
    userUuid,
    _5
    roomUuid,
    _5
    role: userRole,
    _5
    });

  2. Use the token obtained in this request to create a launchOption object:


    _18
    const launchOption = {
    _18
    appId,
    _18
    sdkDomain,
    _18
    pretest: true,
    _18
    courseWareList: [],
    _18
    language: language as LanguageEnum,
    _18
    userUuid: `${userUuid}`,
    _18
    rtmToken: token,
    _18
    roomUuid: `${roomUuid}`,
    _18
    roomType: roomType,
    _18
    roomName: `${roomName}`,
    _18
    userName: userName,
    _18
    roleType: userRole,
    _18
    region: region as EduRegion,
    _18
    duration: +duration * 60,
    _18
    latencyLevel: 2,
    _18
    shareUrl,
    _18
    };

  3. Call launch and use the token to join the classroom:


    _1
    AgoraEduSDK.launch(dom, launchOption);

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.

AccessToken2

AccessToken

Considerations

Parameter consistency

The parameters used to generate the token need to be consistent with the ones you used to launch Flexible Classroom.

App certificate and token

To use the token for authentication, you need to enable the app certificate for your project on Agora Console. Once a project has enabled the app certificate, you must use tokens to authenticate its users.

vundefined