How To Set Bearer Authorization Header In Java
Introduction
Earlier using the Agora RESTful API, you need to pass basic HTTP hallmark or token hallmark.
Basic HTTP authentication
You need to generate a Base64-encoded credential with the Customer ID and Client Hush-hush provided by Agora and pass the credential to the Authorisation
parameter in the asking header. The following products demand bones HTTP authentication:
- Audio SDK/Video SDK/Alive Interactive Streaming Premium/Alive Interactive Streaming Standard
- Cloud Recording
- Existent-time Messaging
- Agora Analytics
Token authentication
Token authentication for the Agora RESTful API is currently simply available for Real-time Messaging. You lot demand to fill the 10-agora-token
and x-agora-uid
fields in the request header with the following information:
- The RTM token generated from your server
- The RTM user ID used to generate the RTM token
Implement HTTP bones authentication or token authentication on the server; otherwise, you may encounter the hazard of data leakage.
Implement Basic HTTP authentication
Implementation
To generate a set of Customer ID and Client Secret, practice the following:
-
In Agora Console, click the account proper noun in the elevation right corner, and click RESTful API from the driblet-down list to enter the RESTful API folio.
-
Click Add a secret, and click OK. A set of Customer ID and Customer Secret is generated.
-
Click Download in the Client Surreptitious column. Read the pop-up window carefully, and save the downloaded
key_and_secret.txt
file in a secure location. -
Utilise the Client ID (fundamental) and Customer Secret (hugger-mugger) to generate a Base64-encoded credential, and pass the Base64-encoded credential to the
Authorization
parameter in the HTTP request header.
Yous can download the Client Secret from Agora Console only in one case. Exist sure to keep it secure.
Sample code
The following sample codes implement bones HTTP authentication and send a request with the Server RESTful API to get the basic data of all current Agora projects.
Coffee
import java.io.IOException; import java.net.URI; import java.cyberspace.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.util.Base64; // HTTP bones hallmark example in Java using the RTC Server RESTful API public class Base64Encoding { public static void main(Cord[] args) throws IOException, InterruptedException { // Client ID final Cord customerKey = "Your client ID"; // Customer secret terminal String customerSecret = "Your client secret"; // Concatenate customer key and customer hole-and-corner and utilize base64 to encode the concatenated string Cord plainCredentials = customerKey + ":" + customerSecret; String base64Credentials = new String(Base64.getEncoder().encode(plainCredentials.getBytes())); // Create authority 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-Blazon", "application/json") .build(); // Transport HTTP request HttpResponse<Cord> response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.torso()); } }
Golang
package main import ( "fmt" "strings" "cyberspace/http" "io/ioutil" "encoding/base64" ) // HTTP basic authentication example in Golang using the RTC Server RESTful API func chief() { // Client ID customerKey := "Your client ID" // Client secret customerSecret := "Your customer secret" // Concatenate customer key and customer undercover and employ 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(``) customer := &http.Client { } req, err := http.NewRequest(method, url, payload) if err != nix { fmt.Println(err) return } // Add Authorization header req.Header.Add("Dominance", "Bones " + base64Credentials) req.Header.Add("Content-Type", "application/json") // Send HTTP asking res, err := client.Do(req) if err != nil { fmt.Println(err) return } defer res.Body.Close() body, err := ioutil.ReadAll(res.Torso) if err != nil { fmt.Println(err) return } fmt.Println(string(trunk)) }
PHP
<?php // HTTP basic authentication instance in PHP using the RTC Server RESTful API // Client ID $customerKey = "Your customer ID"; // Customer secret $customerSecret = "Your customer undercover"; // Concatenate client key and customer hugger-mugger $credentials = $customerKey . ":" . $customerSecret; // Encode with base64 $base64Credentials = base64_encode($credentials); // Create authorization header $arr_header = "Authority: Basic " . $base64Credentials; $curlicue = curl_init(); // Send HTTP request curl_setopt_array($whorl, array( CURLOPT_URL => 'https://api.agora.io/dev/v1/projects', CURLOPT_RETURNTRANSFER => truthful, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'Get', CURLOPT_HTTPHEADER => assortment( $arr_header, 'Content-Blazon: awarding/json' ), )); $response = curl_exec($curl); if($response === simulated) { repeat "Error in cURL : " . curl_error($curl); } curl_close($scroll); echo $response;
C#
using System; using Arrangement.IO; using Organization.Internet; using System.Text; // HTTP basic hallmark example in C# using the RTC Server RESTful API namespace Examples.System.Net { public class WebRequestPostExample { public static void Main() { // Client ID string customerKey = "Your customer ID"; // Customer clandestine string customerSecret = "Your customer secret"; // Concatenate customer key and client secret and employ base64 to encode the concatenated string string plainCredential = customerKey + ":" + customerSecret; // Encode with base64 var plainTextBytes = Encoding.UTF8.GetBytes(plainCredential); string encodedCredential = Catechumen.ToBase64String(plainTextBytes); // Create potency header string authorizationHeader = "Authorization: Bones " + encodedCredential; // Create request object WebRequest request = WebRequest.Create("https://api.agora.io/dev/v1/projects"); request.Method = "Become"; // Add authorisation 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(); Panel.WriteLine(responseFromServer); } response.Close(); } } }
node.js
// HTTP basic authentication case in node.js using the RTC Server RESTful API const https = crave('https') // Customer ID const customerKey = "Your customer ID" // Customer underground const customerSecret = "Your customer secret" // Concatenate customer key and customer secret and employ base64 to encode the concatenated cord const plainCredential = customerKey + ":" + customerSecret // Encode with base64 encodedCredential = Buffer.from(plainCredential).toString('base64') authorizationField = "Bones " + encodedCredential // Prepare request parameters const options = { hostname: 'api.agora.io', port: 443, path: '/dev/v1/projects', method: 'GET', headers: { 'Authorization':authorizationField, 'Content-Blazon': 'application/json' } } // Create request object and send asking const req = https.request(options, res => { console.log(`Condition code: ${res.statusCode}`) res.on('data', d => { process.stdout.write(d) }) }) req.on('mistake', error => { console.fault(error) }) req.finish()
Python
# -- coding utf-eight -- # Python iii # HTTP basic hallmark example in python using the RTC Server RESTful API import base64 import http.customer # Customer ID customer_key = "Your customer ID" # Client underground customer_secret = "Your customer secret" # Concatenate customer fundamental and customer secret and use base64 to encode the concatenated string credentials = customer_key + ":" + customer_secret # Encode with base64 base64_credentials = base64.b64encode(credentials.encode("utf8")) credential = base64_credentials.decode("utf8") # Create connection object with basic URL conn = http.client.HTTPSConnection("api.agora.io") payload = "" # Create Header object headers = {} # Add Authorisation field headers['Dominance'] = 'basic ' + credential headers['Content-Type'] = 'application/json' # Send asking conn.request("GET", "/dev/v1/projects", payload, headers) res = conn.getresponse() information = res.read() print(data.decode("utf-8"))
Implement Token authentication
Implementation
-
Generate the RTM token from your server.
-
Enter the RTM token and the RTM user ID into the
x-agora-token
andten-agora-uid
fields of the HTTP asking header, respectively.
Sample code
The following sample codes implement token hallmark and send a request with the RTM RESTful API to get RTM user events.
Java
import java.io.IOException; import java.net.URI; import coffee.net.http.HttpClient; import coffee.cyberspace.http.HttpRequest; import coffee.net.http.HttpResponse; import java.util.Base64; // Token authentication example in Java using the RTM user events RESTful API public class Base64Encoding { public static void main(Cord[] args) throws IOException, InterruptedException { // RTM Token String token = "Your RTM token"; // User ID used to generate the RTM token String uid = "test_user"; HttpClient client = HttpClient.newHttpClient(); // Create request object HttpRequest asking = 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 together the x-agora-uid field to the header .header("ten-agora-uid", uid) .header("Content-Type", "application/json") .build(); // Transport request HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.body()); } }
Golang
package primary import ( "fmt" "strings" "net/http" "io/ioutil" ) // Token authentication example in Golang using the RTM user events RESTful API func principal() { // RTM Token token := "Your RTM Token" // User ID used to generate the RTM token uid := "test_user" url := "https://api.agora.io/dev/v2/project/<Your App ID>/rtm/vendor/user_events" method := "Become" payload := strings.NewReader(``) client := &http.Client { } req, err := http.NewRequest(method, url, payload) if err != zero { fmt.Println(err) return } // Add the ten-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-Blazon", "application/json") // Send request res, err := client.Practice(req) if err != nil { fmt.Println(err) render } defer res.Body.Shut() trunk, err := ioutil.ReadAll(res.Body) if err != zero { fmt.Println(err) return } fmt.Println(cord(trunk)) }
PHP
<?php // Token authentication example in PHP using the RTM user events RESTful API // RTM Token $token = "Your RTM Token"; // User ID used to generate the RTM 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 = "ten-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 => 'Go', CURLOPT_HTTPHEADER => assortment( $token_header, $uid_header, 'Content-Blazon: application/json' ), )); $response = curl_exec($curl); if($response === false) { echo "Error in cURL : " . curl_error($scroll); } curl_close($whorl); echo $response;
C#
using System; using System.IO; using System.Net; using Organization.Text; // Token hallmark case in C# using the RTM user events RESTful API namespace Examples.Arrangement.Net { public course WebRequestPostExample { public static void Principal() { // RTM Token cord token = "Your RTM Token"; // User ID used to generate the RTM token string uid = "userA"; // Add together the 10-agora-token field to the header cord tokenHeader = "x-agora-token: " + token; // Add the ten-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"); asking.Method = "GET"; // Add header to the request asking.Headers.Add(tokenHeader); request.Headers.Add(uidHeader); asking.ContentType = "application/json"; // Get response WebResponse response = request.GetResponse(); Console.WriteLine(((HttpWebResponse)response).StatusDescription); using (Stream dataStream = response.GetResponseStream()) { StreamReader reader = new StreamReader(dataStream); cord responseFromServer = reader.ReadToEnd(); Console.WriteLine(responseFromServer); } response.Close(); } } }
node.js
// Token authentication example in node.js using the RTM user events RESTful API const https = require('https') // RTM Token token = "Your RTM Token" // User ID used to generate the RTM 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: 'Become', headers: { // Add the 10-agora-token field to the header '10-agora-token':token, // Add together the x-agora-uid field to the header 'x-agora-uid': uid, 'Content-Type': 'application/json' } } const req = https.asking(options, res => { console.log(`Status lawmaking: ${res.statusCode}`) res.on('data', d => { process.stdout.write(d) }) }) req.on('mistake', fault => { console.error(error) }) req.end()
Python
import http.client # Token authentication example in Python using the RTM user events RESTful API # Create connexion object with base URL conn = http.client.HTTPSConnection("api.agora.io") # Create header headers = {} # Add together the x-agora-token field to the header headers['ten-agora-token'] = "Your RTM Token" # Add the ten-agora-uid field to the header, which is the user ID used to generate the RTM token headers['x-agora-uid'] = "test_user" headers['Content-Type'] = 'application/json' payload = "" # Send request conn.asking("Become", "/dev/v2/projection/<Your App ID>/rtm/vendor/user_events", payload, headers) res = conn.getresponse() information = res.read() print(data.decode("utf-8"))
Source: https://docs.agora.io/en/faq/restful_authentication
0 Response to "How To Set Bearer Authorization Header In Java"
Post a Comment