Skip to main content

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 Authorization parameter 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:


_1
Authorization: agora token=<your_token>

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

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.

Use your preferred package manager to install the SDK:


_1
npm install agora-agent-server-sdk

Sample code

The following sample code generates a token and uses it to start a Conversational AI agent.


_56
const https = require('https');
_56
const { generateConvoAIToken } = require('agora-agent-server-sdk');
_56
_56
// App credentials. Keep these on the server and never expose them to clients
_56
const appId = '<your_app_id>';
_56
const appCertificate = '<your_app_certificate>';
_56
_56
// Token parameters. channelName must match properties.channel in the request body
_56
const channelName = '<your_channel_name>';
_56
const agentUid = '<your_agent_uid>'; // Must match agent_rtc_uid in the request body
_56
const tokenExpirationInSeconds = 86400; // Valid range: 1–86400 (24 hours maximum)
_56
_56
// Generate the token
_56
const token = generateConvoAIToken({
_56
appId,
_56
appCertificate,
_56
channelName,
_56
account: agentUid,
_56
tokenExpire: tokenExpirationInSeconds,
_56
});
_56
_56
// Use the token to start a Conversational AI agent
_56
const data = JSON.stringify({
_56
name: '<agent_identifier>',
_56
pipeline_id: '<your_agents_pipeline_id>',
_56
properties: {
_56
channel: channelName,
_56
// The token the agent uses to join the RTC channel. This is a separate
_56
// token from the Authorization header token, but in most cases the same
_56
// value can be used for both.
_56
token: token,
_56
agent_rtc_uid: agentUid,
_56
remote_rtc_uids: ['<remote_user_uid>'],
_56
enable_string_uid: false,
_56
},
_56
});
_56
_56
const options = {
_56
hostname: 'api.agora.io',
_56
path: `/api/conversational-ai-agent/v2/projects/${appId}/join`,
_56
method: 'POST',
_56
headers: {
_56
'Authorization': 'agora token=' + token,
_56
'Content-Type': 'application/json',
_56
'Content-Length': Buffer.byteLength(data),
_56
},
_56
};
_56
_56
const req = https.request(options, (res) => {
_56
console.log(`Status code: ${res.statusCode}`);
_56
res.on('data', (d) => { process.stdout.write(d); });
_56
});
_56
_56
req.on('error', (error) => { console.error(error); });
_56
req.write(data);
_56
req.end();

To use string UIDs, pass a string value for agentUid 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

Use your preferred package manager to install the library:


_1
npm install agora-token

Sample code

The following sample code generates a token and uses it to start a Conversational AI agent.


_59
const https = require('https');
_59
const { RtcTokenBuilder, RtcRole } = require('agora-token');
_59
_59
// App credentials. Keep these on the server and never expose them to clients
_59
const appId = '<your_app_id>';
_59
const appCertificate = '<your_app_certificate>';
_59
_59
// Token parameters. channelName must match properties.channel in the request body
_59
const channelName = '<your_channel_name>';
_59
const agentUid = '<your_agent_uid>'; // Must match agent_rtc_uid in the request body
_59
const tokenExpirationInSeconds = 86400; // Valid range: 1–86400 (24 hours maximum)
_59
const privilegeExpirationInSeconds = 86400;
_59
_59
// Generate a combined RTC + RTM token
_59
const token = RtcTokenBuilder.buildTokenWithRtm(
_59
appId,
_59
appCertificate,
_59
channelName,
_59
agentUid,
_59
RtcRole.PUBLISHER,
_59
tokenExpirationInSeconds,
_59
privilegeExpirationInSeconds
_59
);
_59
_59
// Use the token to start a Conversational AI agent
_59
const data = JSON.stringify({
_59
name: '<agent_identifier>',
_59
pipeline_id: '<your_agents_pipeline_id>',
_59
properties: {
_59
channel: channelName,
_59
// The token the agent uses to join the RTC channel. This is a separate
_59
// token from the Authorization header token, but in most cases the same
_59
// value can be used for both.
_59
token: token,
_59
agent_rtc_uid: agentUid,
_59
remote_rtc_uids: ['<remote_user_uid>'],
_59
enable_string_uid: false,
_59
},
_59
});
_59
_59
const options = {
_59
hostname: 'api.agora.io',
_59
path: `/api/conversational-ai-agent/v2/projects/${appId}/join`,
_59
method: 'POST',
_59
headers: {
_59
'Authorization': 'agora token=' + token,
_59
'Content-Type': 'application/json',
_59
'Content-Length': Buffer.byteLength(data),
_59
},
_59
};
_59
_59
const req = https.request(options, (res) => {
_59
console.log(`Status code: ${res.statusCode}`);
_59
res.on('data', (d) => { process.stdout.write(d); });
_59
});
_59
_59
req.on('error', (error) => { console.error(error); });
_59
req.write(data);
_59
req.end();

To use string UIDs, pass a string value for agentUid 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 Authorization header token authenticates your server's REST API calls to Agora. The properties.token field 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 setting advanced_features.enable_rtm to true. For details, see Generate a token with RTC and Signaling privileges.
info

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:

  1. In Agora Console, click Developer Toolkit > RESTful API.

    RESTful API

  2. Click Add a secret, and click OK. A set of customer ID and customer secret is generated.

  3. Click Download in the Customer Secret column. Read the pop-up window carefully, and save the downloaded key_and_secret.txt file in a secure location.

  4. Use the customer ID (key) and customer secret (secret) to generate a Base64-encoded credential, and pass the Base64-encoded credential to the Authorization parameter 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::


_1
Authorization: Basic NDI1OTQ3N2I4MzYy...YwZjA=a

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.

caution

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.

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))}