RESTful authentication
Conversational AI Engine RESTful API requires REST authentication. The following REST authentication methods are available:
-
Token authentication
Token authentication uses an RTC token generated on your server using your app ID and app certificate.
-
Basic HTTP authentication
Generate a Base64-encoded credential with the customer ID and customer secret provided by Agora and pass the credential with the
Authorizationparameter in the request header.
Implement token authentication
Token authentication uses an RTC token generated on your server using your app ID and app certificate. A token is scoped to a specific app ID and channel, making it the preferred method for production environments.
To authenticate using a token, include the Authorization header in each request:
Prerequisites
Before you begin, ensure that you have the following from Agora Console:
- App ID: A unique string that identifies your project.
- App Certificate: A string used to generate tokens.
Never expose your App Certificate in client-side code or public repositories. Generate tokens on your server only.
The Agora RESTful API only supports HTTPS with TLS 1.0, 1.1, or 1.2 for encrypted communication. Requests over plain HTTP are not supported and will fail to connect.
Using the Conversational AI SDK
If you are already using the Conversational AI SDK in your project, use the SDK token generation utility to generate tokens. If you want a standalone token generation dependency without the full SDK, use the Agora token builder library.
Install the SDK
The Agora Conversational AI SDKs include a built-in token generation utility. Install the SDK for your language, or skip this step if it is already part of your project.
- Node.js
- Golang
- Python
Use your preferred package manager to install the SDK:
Add it as a dependency using go get:
Use pip to install the SDK:
Sample code
The following sample code generates a token and uses it to start a Conversational AI agent.
- Node.js
- Golang
- Python
To use string UIDs, pass a string value for agentUid and set enable_string_uid to true in the request body accordingly.
To use string UIDs, pass a string value for agentUid and set enable_string_uid to true in the request body.
To use string UIDs, pass a string value for agent_uid and set enable_string_uid to True in the request body accordingly.
Using the token builder library
The AgoraDynamicKey repository provides open-source token generation libraries for multiple languages.
Install the library
- Node.js
- Golang
- Python
Use your preferred package manager to install the library:
Add it as a dependency using go get:
Clone the AgoraDynamicKey repository and navigate to the Python3 token builder source directory:
Sample code
The following sample code generates a token and uses it to start a Conversational AI agent.
- Node.js
- Golang
- Python
To use string UIDs, pass a string value for agentUid and set enable_string_uid to true in the request body accordingly.
To use string UIDs, pass a string value for agentUid and set enable_string_uid to true in the request body.
To use string UIDs, pass a string value for agent_uid and set enable_string_uid to True in the request body accordingly.
Additional considerations
- Token expiry: Tokens expire after a maximum of 86400 seconds (24 hours). Generate a fresh token for each agent session.
- Two tokens: The
Authorizationheader token authenticates your server's REST API calls to Agora. Theproperties.tokenfield is the token the agent uses to join the RTC channel. This is typically the same token, but must also include RTM privileges if you enable the Signaling service by settingadvanced_features.enable_rtmtotrue. For details, see Generate a token with RTC and Signaling privileges.
Implement authentication on the server to mitigate the risk of data leakage.
Implement basic HTTP authentication
Generate Customer ID and Customer Secret
To generate a set of customer ID and customer secret, do the following:
-
In Agora Console, click Developer Toolkit > RESTful API.

-
Click Add a secret, and click OK. A set of customer ID and customer secret is generated.
-
Click Download in the Customer Secret column. Read the pop-up window carefully, and save the downloaded
key_and_secret.txtfile in a secure location. -
Use the customer ID (key) and customer secret (secret) to generate a Base64-encoded credential, and pass the Base64-encoded credential to the
Authorizationparameter in the HTTP request header.
You can download the customer secret from Agora Console only once. Be sure to keep it secure.
Generate an authorization header using a third-party tool
For testing and debugging, you can use a third-party online tool to quickly generate your Authorization header. Enter your Customer ID as the Username and your Customer Secret as the Password. Your generated header should look like this::
Basic authentication sample code
The following sample code implements basic HTTP authentication and sends a RESTful API request to get the basic information of all your current Agora projects.
The Agora RESTful API only supports HTTPS with TLS 1.0, 1.1, or 1.2 for encrypted communication. Requests over plain HTTP are not supported and will fail to connect.
- Golang
- Node.js
- PHP
- Python
- Java
- C#
package mainimport ( "fmt" "strings" "net/http" "io/ioutil" "encoding/base64")// HTTPS basic authentication example in Golang using the <Vg k="VSDK" /> Server RESTful APIfunc main() { // Customer ID customerKey := "Your customer ID" // Customer secret customerSecret := "Your customer secret" // Concatenate customer key and customer secret and use base64 to encode the concatenated string plainCredentials := customerKey + ":" + customerSecret base64Credentials := base64.StdEncoding.EncodeToString([]byte(plainCredentials)) url := "https://api.agora.io/dev/v1/projects" method := "GET" payload := strings.NewReader(``) client := &http.Client { } req, err := http.NewRequest(method, url, payload) if err != nil { fmt.Println(err) return } // Add Authorization header req.Header.Add("Authorization", "Basic " + base64Credentials) req.Header.Add("Content-Type", "application/json") // Send HTTP request res, err := client.Do(req) if err != nil { fmt.Println(err) return } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if err != nil { fmt.Println(err) return } fmt.Println(string(body))}// HTTP basic authentication example in node.js using the <Vg k="VSDK" /> Server RESTful APIconst https = require('https')// Customer IDconst customerKey = "Your customer ID"// Customer secretconst customerSecret = "Your customer secret"// Concatenate customer key and customer secret and use base64 to encode the concatenated stringconst plainCredential = customerKey + ":" + customerSecret// Encode with base64encodedCredential = Buffer.from(plainCredential).toString('base64')authorizationField = "Basic " + encodedCredential// Set request parametersconst options = { hostname: 'api.agora.io', port: 443, path: '/dev/v1/projects', method: 'GET', headers: { 'Authorization':authorizationField, 'Content-Type': 'application/json' }}// Create request object and send requestconst req = https.request(options, res => { console.log(`Status code: ${res.statusCode}`) res.on('data', d => { process.stdout.write(d) })})req.on('error', error => { console.error(error)})req.end()<?php// HTTP basic authentication example in PHP using the Agora Server RESTful API// Customer ID and secret$customerKey = "Your customer ID"; // Replace with your actual customer ID$customerSecret = "Your customer secret"; // Replace with your actual customer secret// Concatenate customer key and customer secret$credentials = $customerKey . ":" . $customerSecret;// Encode with base64$base64Credentials = base64_encode($credentials);// Create authorization header$authHeader = "Authorization: Basic " . $base64Credentials;// Initialize cURL$curl = curl_init();// Set cURL optionscurl_setopt_array($curl, [ CURLOPT_URL => 'https://api.agora.io/dev/v1/projects', CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'GET', CURLOPT_HTTPHEADER => [ $authHeader, 'Content-Type: application/json', ],]);// Execute cURL request$response = curl_exec($curl);// Check for cURL errorsif ($response === false) { echo "Error in cURL: " . curl_error($curl);} else { // Output the response echo $response;}// Close cURL sessioncurl_close($curl);?># -- coding utf-8 --# Python 3# HTTP basic authentication example in python using the <Vg k="VSDK" /> Server RESTful APIimport base64import http.client# Customer IDcustomer_key = "Your customer ID"# Customer secretcustomer_secret = "Your customer secret"# Concatenate customer key and customer secret and use base64 to encode the concatenated stringcredentials = customer_key + ":" + customer_secret# Encode with base64base64_credentials = base64.b64encode(credentials.encode("utf8"))credential = base64_credentials.decode("utf8")# Create connection object with basic URLconn = http.client.HTTPSConnection("api.agora.io")payload = ""# Create Header objectheaders = {}# Add Authorization fieldheaders['Authorization'] = 'basic ' + credentialheaders['Content-Type'] = 'application/json'# Send requestconn.request("GET", "/dev/v1/projects", payload, headers)res = conn.getresponse()data = res.read()print(data.decode("utf-8"))import java.io.IOException;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.util.Base64;// HTTP basic authentication example in Java using the <Vg k="VSDK" /> Server RESTful APIpublic class Base64Encoding { public static void main(String[] args) throws IOException, InterruptedException { // Customer ID final String customerKey = "Your customer ID"; // Customer secret final String customerSecret = "Your customer secret"; // Concatenate customer key and customer secret and use base64 to encode the concatenated string String plainCredentials = customerKey + ":" + customerSecret; String base64Credentials = new String(Base64.getEncoder().encode(plainCredentials.getBytes())); // Create authorization header String authorizationHeader = "Basic " + base64Credentials; HttpClient client = HttpClient.newHttpClient(); // Create HTTP request object HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.agora.io/dev/v1/projects")) .GET() .header("Authorization", authorizationHeader) .header("Content-Type", "application/json") .build(); // Send HTTP request HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.body()); }}using System;using System.IO;using System.Net;using System.Text;// HTTP basic authentication example in C# using the <Vg k="VSDK" /> Server RESTful APInamespace Examples.System.Net{ public class WebRequestPostExample { public static void Main() { // Customer ID string customerKey = "Your customer ID"; // Customer secret string customerSecret = "Your customer secret"; // Concatenate customer key and customer secret and use base64 to encode the concatenated string string plainCredential = customerKey + ":" + customerSecret; // Encode with base64 var plainTextBytes = Encoding.UTF8.GetBytes(plainCredential); string encodedCredential = Convert.ToBase64String(plainTextBytes); // Create authorization header string authorizationHeader = "Authorization: Basic " + encodedCredential; // Create request object WebRequest request = WebRequest.Create("https://api.agora.io/dev/v1/projects"); request.Method = "GET"; // Add authorization header request.Headers.Add(authorizationHeader); request.ContentType = "application/json"; WebResponse response = request.GetResponse(); Console.WriteLine(((HttpWebResponse)response).StatusDescription); using (Stream dataStream = response.GetResponseStream()) { StreamReader reader = new StreamReader(dataStream); string responseFromServer = reader.ReadToEnd(); Console.WriteLine(responseFromServer); } response.Close(); } }}