RESTful authentication
Before using Signaling RESTful API, set up REST authentication. The following REST authentication methods are available:
-
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.
-
AccessToken2 authentication
Fill in the
Authorization
field withagora token=
followed by the Signaling SDK AccessToken2 generated from your server.
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.txt
file 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
Authorization
parameter in the HTTP request header.
You can download the customer secret from Agora Console only once. Be sure to keep it secure.
Basic authentication sample code
The following sample code implements basic HTTP authentication and sends a request with the Server RESTful API to get the basic information of all current Agora projects.
- Java
- Golang
- PHP
- C#
- Node.js
- Python
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()); }}
package mainimport ( "fmt" "strings" "net/http" "io/ioutil" "encoding/base64")// HTTP 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))}
<?php// HTTP basic authentication example in PHP using the <Vg k="VSDK" /> Server RESTful API// Customer ID$customerKey = "Your customer ID";// Customer secret$customerSecret = "Your customer secret";// Concatenate customer key and customer secret$credentials = $customerKey . ":" . $customerSecret;// Encode with base64$base64Credentials = base64_encode($credentials);// Create authorization header$arr_header = "Authorization: Basic " . $base64Credentials;$curl = curl_init();// Send HTTP requestcurl_setopt_array($curl, array( 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 => array( $arr_header, 'Content-Type: application/json' ),));$response = curl_exec($curl);if($response === false) { echo "Error in cURL : " . curl_error($curl);}curl_close($curl);echo $response;
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(); } }}
// 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()
# -- 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"))
Implement token authentication
-
Generate the token for your app.
-
Enter the Signaling token and the Signaling user ID into the
x-agora-token
andx-agora-uid
fields of the HTTP request header, respectively.
AccessToken2 authentication sample code
The following sample codes implement AccessToken2 authentication and send a request with the Signaling RESTful API to get Signaling user events.
- Java
- Golang
- Node.js
- Python
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 APIclass 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()); }}
package mainimport ( "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 APIfunc 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}
// Token authentication example in node.js using the Signaling user events RESTful APIconst https = require('https')// Signaling Tokenvar token_value = "input your token here"// App IDvar 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 parametersconst 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()
import http.client# Token authentication example in Python using the Signaling user events RESTful API# Signaling Tokentoken_value = "input your token here"# App IDapp_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 URLconn = http.client.HTTPSConnection("api.agora.io")# Create headerheaders = {}# Add authorization headerheaders['Authorization'] = auth_valueheaders['Content-Type'] = 'application/json'payload = ""# Send requestconn.request("GET", url_path, payload, headers)res = conn.getresponse()data = res.read()print(data.decode("utf-8"))