Skip to main content

Authenticate REST calls

Before using an Agora RESTful API, you need to setup REST authentication.

Available REST authentication methods are:

  • AccessToken2

    You need to fill the Authorization: agora token= field with the Signaling SDK AccessToken2 generated from your server.

  • AccessToken

    You need to fill the x-agora-token and x-agora-uid fields in the request header with the following information:

    • The Signaling SDK AccessToken generated from your server
    • The Signaling SDK user ID used to generate the Signaling token

    Implement HTTP basic authentication or token authentication on the server; otherwise, you may encounter the risk of data leakage.

Implement authentication on the server; otherwise, you may encounter the risk of data leakage.

Implement token authentication

  1. Generate the token for your app.

  2. Enter the Signaling token and the Signaling user ID into the x-agora-token and x-agora-uid fields of the HTTP request header, respectively.

Sample code for AccessToken2

The following sample codes implement AccessToken2 authentication and send a request with the Signaling RESTful API to get Signaling user events.

Java

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;


// Token authentication example in Java using the Signaling user events RESTful API
class TokenAuthExample {
public static void main(String[] args) throws IOException, InterruptedException {
// Signaling token
final String tokenValue = "input your token value here";
// App ID
final String appID = "input your app ID here";

String urlStr = String.format("https://api.agora.io/dev/v2/project/%s/rtm/vendor/user_events", appID);
String authValue = String.format("agora token=%s", tokenValue);

// Create request object
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(urlStr))
.GET()
.header("Authorization", authValue)
.header("Content-Type", "application/json")
.build();

// Send request
HttpClient client = HttpClient.newHttpClient();
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());

System.out.println(response.body());
}
}
Copy

Golang

package main

import (
"fmt"
"io/ioutil"
"net/http"
)

func main() {
if err := tokenAuthExamle(); err != nil {
panic(err)
}
}

// Token authentication example in Golang using the Signaling user events RESTful API
func tokenAuthExamle() error {
var (
// Signaling Token
tokenValue = "input the token value here"
// App ID
appID = "input your app ID here"
urlstr = fmt.Sprintf("https://api.agora.io/dev/v2/project/%s/rtm/vendor/user_events", appID)
authValue = fmt.Sprintf("agora token=%s", tokenValue)
)

// Create request object
req, err := http.NewRequest(http.MethodGet, urlstr, nil)
if err != nil {
return fmt.Errorf("failed to new http request, %w", err)
}
// Set Authorization header
req.Header.Set("Authorization", authValue)
req.Header.Set("Content-Type", "application/json")

// Send request
resp, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("failed to send request, %w", err)
}
defer resp.Body.Close()

// Read response body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response body, %w", err)
}

// Respond status code
if resp.StatusCode/100 != 2 {
return fmt.Errorf("StatusCode(%d) != 2xx, %s", resp.StatusCode, string(body))
}

// Print response body
fmt.Println(string(body))
return nil
}
Copy

node.js

// Token authentication example in node.js using the Signaling user events RESTful API
const https = require('https')


// Signaling Token
var token_value = "input your token here"
// App ID
var app_id = "input your app ID"

var url_path = `/dev/v2/project/${app_id}/rtm/vendor/user_events`
var auth_token = `agora token=${token_value}`

// Set request parameters
const options = {
hostname: 'api.agora.io',
port: 443,
path: url_path,
method: 'GET',
headers: {
// Add the authorization field to the header
'Authorization': auth_token,
'Content-Type': 'application/json'
}
}

const 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()
Copy

Python

import http.client
# Token authentication example in Python using the Signaling user events RESTful API

# Signaling Token
token_value = "input your token here"
# App ID
app_id = "input your app ID here"


url_path = "/dev/v2/project/{0}/rtm/vendor/user_events".format(app_id)
auth_value = "agora token={0}".format(token_value)

# Create connection object with base URL
conn = http.client.HTTPSConnection("api.agora.io")
# Create header
headers = {}
# Add authorization header
headers['Authorization'] = auth_value
headers['Content-Type'] = 'application/json'
payload = ""
# Send request
conn.request("GET", url_path, payload, headers)

res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
Copy

Sample code for AccessToken

The following sample codes implement AccessToken authentication and send a request with the Signaling RESTful API to get Signaling user events.

Java

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;


// Token authentication example in Java using the Signaling user events RESTful API
public class Base64Encoding {

public static void main(String[] args) throws IOException, InterruptedException {

// Signaling Token
String token = "Your Signaling token";
// User ID used to generate the Signaling token
String uid = "test_user";

HttpClient client = HttpClient.newHttpClient();


// Create request object
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.agora.io/dev/v2/project/<Your App ID>/rtm/vendor/user_events"))
.GET()
// Add the x-agora-token field to the header
.header("x-agora-token", token )
// Add the x-agora-uid field to the header
.header("x-agora-uid", uid)
.header("Content-Type", "application/json")
.build();
// Send request
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());

System.out.println(response.body());
}
}
Copy

Golang

package main


import (
"fmt"
"strings"
"net/http"
"io/ioutil"
)

// Token authentication example in Golang using the Signaling user events RESTful API
func main() {

// Signaling Token
token := "Your Signaling Token"
// User ID used to generate the Signaling token
uid := "test_user"


url := "https://api.agora.io/dev/v2/project/<Your App ID>/rtm/vendor/user_events"
method := "GET"

payload := strings.NewReader(``)

client := &http.Client {
}
req, err := http.NewRequest(method, url, payload)

if err != nil {
fmt.Println(err)
return
}
// Add the x-agora-token field to the header
req.Header.Add("x-agora-token", token)
// Add the x-agora-uid field to the header
req.Header.Add("x-agora-uid", uid)
req.Header.Add("Content-Type", "application/json")

// Send 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))
}
Copy

PHP

<?php
// Token authentication example in PHP using the Signaling user events RESTful API

// Signaling Token
$token = "Your Signaling Token";
// User ID used to generate the Signaling token
$uid = "test_user";
// Add the x-agora-token field to the header
$token_header = "x-agora-token: " . $token;
// Add the x-agora-uid field to the header
$uid_header = "x-agora-uid: " . $uid;

$curl = curl_init();
// Send request
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.agora.io/dev/v2/project/<Your App ID>/rtm/vendor/user_events',
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 => array(
$token_header,
$uid_header,
'Content-Type: application/json'
),
));

$response = curl_exec($curl);

if($response === false) {
echo "Error in cURL : " . curl_error($curl);
}

curl_close($curl);

echo $response;
Copy

C#

using System;
using System.IO;
using System.Net;
using System.Text;
// Token authentication example in C# using the Signaling user events RESTful API
namespace Examples.System.Net
{
public class WebRequestPostExample
{
public static void Main()
{

// Signaling Token
string token = "Your Signaling Token";
// User ID used to generate the Signaling token
string uid = "userA";
// Add the x-agora-token field to the header
string tokenHeader = "x-agora-token: " + token;
// Add the x-agora-uid field to the header
string uidHeader = "x-agora-uid: " + uid;

WebRequest request = WebRequest.Create("https://api.agora.io/dev/v2/project/<Your App ID>/rtm/vendor/user_events");
request.Method = "GET";

// Add header to the request
request.Headers.Add(tokenHeader);
request.Headers.Add(uidHeader);

request.ContentType = "application/json";

// Get response
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();
}
}
}
Copy

node.js

// Token authentication example in node.js using the Signaling user events RESTful API
const https = require('https')


// Signaling Token
token = "Your Signaling Token"
// User ID used to generate the Signaling token
uid = "test_user"

// Set request parameters
const options = {
hostname: 'api.agora.io',
port: 443,
path: '/dev/v2/project/<Your App ID>/rtm/vendor/user_events',
method: 'GET',
headers: {
// Add the x-agora-token field to the header
'x-agora-token':token,
// Add the x-agora-uid field to the header
'x-agora-uid': uid,
'Content-Type': 'application/json'
}
}

const 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()
Copy

Python

import http.client
# Token authentication example in Python using the Signaling user events RESTful API

# Create connection object with base URL
conn = http.client.HTTPSConnection("api.agora.io")
# Create header
headers = {}
# Add the x-agora-token field to the header
headers['x-agora-token'] = "Your Signaling Token"
# Add the x-agora-uid field to the header, which is the user ID used to generate the Signaling token
headers['x-agora-uid'] = "test_user"
headers['Content-Type'] = 'application/json'
payload = ""
# Send request
conn.request("GET", "/dev/v2/project/<Your App ID>/rtm/vendor/user_events", payload, headers)

res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
Copy
vundefined