Quickstart: Access TURN relays
This quickstart shows how to retrieve a network relay token to access Azure Communication Services TURN servers.
Prerequisites
- An Azure account with an active subscription. Create an account for free
- An active Azure Communication Services resource, see create a Communication Services resource if you do not have one.
Note
Find the finalized code for this quickstart on GitHub
Prerequisite check
- In a terminal or command window, run the
dotnetcommand to check that the .NET SDK is installed.
Setting Up
Create a new C# application
- In a console window (such as cmd, PowerShell, or Bash), use the
dotnet newcommand to create a new console app with the nameRelayTokenQuickstart. This command creates a simple "Hello World" C# project with a single source file: Program.cs.
dotnet new console -o RelayTokenQuickstart
- Change your directory to the newly created app folder and use the
dotnet buildcommand to compile your application.
cd RelayTokenQuickstart
dotnet build
Install the package
While still in the application directory, install the Azure Communication Services Identity and NetworkTraversal library for .NET package by using the dotnet add package command.
dotnet add package Azure.Communication.Identity
dotnet add package Azure.Communication.NetworkTraversal
Set up the app framework
From the project directory:
- Open Program.cs file in a text editor
- Add a
usingdirective to include theAzure.Communication.Identity,System.Threading.Tasks, andSystem.Net.Http - Update the
Mainmethod declaration to support async code
Here's the code:
using System;
using Azure.Communication.Identity;
using Azure;
using System.Collections.Generic;
using Azure.Communication.NetworkTraversal;
namespace RelayTokenQuickstart
{
class Program
{
static async Task Main(string[] args)
{
Console.WriteLine("Azure Communication Services - User Relay Token Quickstart");
// Quickstart code goes here
}
}
}
Authenticate the client
Initialize a CommunicationIdentityClient with your connection string. The code below retrieves the connection string for the resource from an environment variable. If you created the environment variable after you launched the application, you will need to close and reopen the editor, IDE, or shell running it to access the variable.
Add the following code to the Main method:
// This code demonstrates how to fetch your connection string
// from an environment variable.
string connectionString = Environment.GetEnvironmentVariable("COMMUNICATION_SERVICES_CONNECTION_STRING");
var client = new CommunicationIdentityClient(connectionString);
Create an identity
Azure Communication Services maintains a lightweight identity directory. Use the createUser method to create a new entry in the directory with a unique Id. Store received identity with mapping to your application's users. For example, by storing them in your application server's database. The identity is required later to issue access tokens.
var identityResponse = await client.CreateUserAsync().Result;
var identity = identityResponse.Value;
Console.WriteLine($"\nCreated an identity with ID: {identity.Id}");
Exchange the user access token for a relay token
Call the Azure Communication token service to exchange the user access token for a TURN service token
var relayClient = new CommunicationRelayClient("COMMUNICATION_SERVICES_CONNECTION_STRING");
Response<CommunicationRelayConfiguration> turnTokenResponse = await relayClient.GetRelayConfigurationAsync(identity).Result;
DateTimeOffset turnTokenExpiresOn = turnTokenResponse.Value.ExpiresOn;
IReadOnlyList<CommunicationIceServer> iceServers = turnTokenResponse.Value.IceServers;
Console.WriteLine($"Expires On: {turnTokenExpiresOn}");
foreach (CommunicationIceServer iceServer in iceServers)
{
foreach (string url in iceServer.Urls)
{
Console.WriteLine($"TURN Url: {url}");
}
Console.WriteLine($"TURN Username: {iceServer.Username}");
Console.WriteLine($"TURN Credential: {iceServer.Credential}");
}
Run the code
Run the application from your application directory with the dotnet run command.
dotnet run
Note
Find the finalized code for this quickstart on GitHub
Setting Up
Create a new Node.js Application
Open your terminal or command window create a new directory for your app, and navigate to it.
mkdir relay-token-quickstart && cd relay-token-quickstart
Run npm init -y to create a package.json file with default settings.
npm init -y
Install the package
Use the npm install command to install the Azure Communication Services Identity client library and Network Traversal library for JavaScript.
npm install @azure/communication-identity --save
npm install @azure/communication-network-traversal --save
The --save option lists the library as a dependency in your package.json file.
Set up the app framework
From the project directory:
Open a new text file in your code editor
Add the
requiredirectives to the top of file to use the Azure Communication Identity SDK and Network Traversal SDKCreate the structure for the program, including basic exception handling
Use the following code to begin:
const { CommunicationIdentityClient } = require("@azure/communication-identity"); const { CommunicationRelayClient } = require("@azure/communication-network-traversal");; const main = async () => { console.log("Azure Communication Services - Relay Token Quickstart") // Quickstart code goes here }; main().catch((error) => { console.log("Encountered and error"); console.log(error); })Save the new file as relay-token.js in the user-tokens-quickstart directory.
Authenticate the client
Instantiate a CommunicationIdentityClient with your connection string. The code below retrieves the connection string for the resource from an environment variable named COMMUNICATION_SERVICES_CONNECTION_STRING. Learn how to manage your resource's connection string.
Add the following code to the main method:
// This code demonstrates how to fetch your connection string
// from an environment variable.
const connectionString = process.env['COMMUNICATION_SERVICES_CONNECTION_STRING'];
// Instantiate the identity client
const identityClient = new CommunicationIdentityClient(connectionString);
Create an identity
Azure Communication Services maintains a lightweight identity directory. Use the createUser method to create a new entry in the directory with a unique Id. Store received identity with mapping to your application's users. For example, by storing them in your application server's database. The identity is required later to issue access tokens.
let identityResponse = await identityClient.createUser();
console.log(`\nCreated an identity with ID: ${identityResponse.communicationUserId}`);
Exchange the user access token for a relay token
Call the Azure Communication token service to exchange the user access token for a TURN service token
const relayClient = new CommunicationRelayClient(connectionString);
console.log("Getting relay configuration");
const config = await relayClient.getRelayConfiguration(identityResponse);
console.log("RelayConfig", config);
Use the token on the client as an ICE candidate
The token can now be deserialized and added and an ICE candidate with WebRTC in the client browser
var configuration = { iceServers: iceServers };
var peerConnection = new RTCPeerConnection(configuration);
Run the code
From a console prompt, navigate to the directory containing the issue-token.js file, then execute the following node command to run the app.
node ./relay-token.js
Note
Find the finalized code for this quickstart on GitHub
Prerequisites for Python
An Azure account with an active subscription. Create an account for free.
- Python 2.7 or 3.6+.
- An active Communication Services resource and connection string. Create a Communication Services resource.
Setting Up
Create a new Python application
Open your terminal or command window create a new directory for your app, and navigate to it.
mkdir access-tokens-quickstart && cd relay-tokens-quickstartUse a text editor to create a file called issue-relay-tokens.py in the project root directory and add the structure for the program, including basic exception handling. You'll add all the source code for this quickstart to this file in the following sections.
import os from azure.communication.networktraversal import CommunicationRelayClient from azure.identity import DefaultAzureCredential from azure.communication.identity import CommunicationIdentityClient try: print("Azure Communication Services - Access Relay Configuration Quickstart") # Quickstart code goes here except Exception as ex: print("Exception:") print(ex)
Install the package
While still in the application directory, install the Azure Communication Services Identity SDK for Python package by using the pip install command.
pip install azure-communication-identity
pip install azure.communication.networktraversal
Authenticate the client
Instantiate a CommunicationIdentityClient with your resource's access key and endpoint. The code below retrieves the connection string for the resource from an environment variable named COMMUNICATION_SERVICES_CONNECTION_STRING. Learn how to manage your resource's connection string.
Add this code inside the try block:
# You can find your endpoint and access token from your resource in the Azure Portal
connection_str = "endpoint=ENDPOINT;accessKey=KEY"
endpoint = "https://<RESOURCE_NAME>.communication.azure.com"
# To use Azure Active Directory Authentication (DefaultAzureCredential) make sure to have
# AZURE_TENANT_ID, AZURE_CLIENT_ID and AZURE_CLIENT_SECRET as env variables.
# We also need Identity client to get a User Identifier
identity_client = CommunicationIdentityClient(endpoint, DefaultAzureCredential())
relay_client = CommunicationRelayClient(endpoint, DefaultAzureCredential())
#You can also authenticate using your connection string
identity_client = CommunicationIdentityClient.from_connection_string(self.connection_string)
relay_client = CommunicationRelayClient.from_connection_string(self.connection_string)
Create a user from identity
Azure Communication Services maintains a lightweight identity directory. Use the create_user method to create a new entry in the directory with a unique Id. Store received identity with mapping to your application's users. For example, by storing them in your application server's database. The identity is required later to issue access tokens.
user = identity_client.create_user()
Getting the relay configuration
Call the Azure Communication token service to exchange the user access token for a TURN service token
relay_configuration = relay_client.get_relay_configuration(user)
for iceServer in config.ice_servers:
assert iceServer.username is not None
print('Username: ' + iceServer.username)
assert iceServer.credential is not None
print('Credential: ' + iceServer.credential)
assert iceServer.urls is not None
for url in iceServer.urls:
print('Url:' + url)
Run the code
From a console prompt, navigate to the directory containing the issue-relay-tokens.py file, then execute the following python command to run the app.
python ./issue-relay-tokens.py
Note
Find the finalized code for this quickstart on GitHub
Prerequisites for Java
- An Azure account with an active subscription. Create an account for free.
- Java Development Kit (JDK) version 8 or above.
- Apache Maven.
- A deployed Communication Services resource and connection string. Create a Communication Services resource.
Setting Up
Create a new Java application
Open your terminal or command window. Navigate to the directory where you'd like to create your Java application. Run the command below to generate the Java project from the maven-archetype-quickstart template.
mvn archetype:generate -DgroupId=com.communication.quickstart -DartifactId=communication-quickstart -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=false
You'll notice that the 'generate' task created a directory with the same name as the artifactId. Under this directory, the src/main/java directory contains the project source code, the src/test/java directory contains the test source, and the pom.xml file is the project's Project Object Model, or POM.
Install the package
Open the pom.xml file in your text editor. Add the following dependency element to the group of dependencies.
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-communication-identity</artifactId>
<version>1.0.0</version>
</dependency>
Set up the app framework
From the project directory:
- Navigate to the
/src/main/java/com/communication/quickstartdirectory - Open the
App.javafile in your editor - Replace the
System.out.println("Hello world!");statement - Add
importdirectives
Use the following code to begin:
package com.communication.quickstart;
import com.azure.communication.common.*;
import com.azure.communication.identity.*;
import com.azure.communication.identity.models.*;
import com.azure.core.credential.*;
import com.communication.network.traversal.*;
import java.io.IOException;
import java.time.*;
import java.util.*;
public class App
{
public static void main( String[] args ) throws IOException
{
System.out.println("Azure Communication Services - Network Credentials Quickstart");
// Quickstart code goes here
}
}
Authenticate the client
Instantiate a CommunicationIdentityClient with your resource's access key and endpoint. Learn how to manage your resource's connection string. In addition, you can initialize the client with any custom HTTP client the implements the com.azure.core.http.HttpClient interface.
Add the following code to the main method:
// Your can find your endpoint and access key from your resource in the Azure portal
String endpoint = "https://<RESOURCE_NAME>.communication.azure.com";
String accessKey = "SECRET";
CommunicationRelayClient communicationRelayClient = new CommunicationRelayClientBuilder()
.endpoint(endpoint)
.credential(new DefaultAzureCredentialBuilder().build())
.buildClient();
You can also provide the entire connection string using the connectionString() function instead of providing the endpoint and access key.
// Your can find your connection string from your resource in the Azure portal
String connectionString = "<connection_string>";
CommunicationRelayClient communicationRelayClient = new CommunicationRelayClientBuilder()
.connectionString(connectionString)
.buildClient();
Create an identity
Azure Communication Services maintains a lightweight identity directory. Use the createUser method to create a new entry in the directory with a unique Id. Store received identity with mapping to your application's users. For example, by storing them in your application server's database. The identity is required later to issue access tokens.
CommunicationUserIdentifier user = communicationIdentityClient.createUser();
System.out.println("\nCreated an identity with ID: " + user.getId());
Getting the relay configuration
Call the Azure Communication token service to exchange the user access token for a TURN service token
CommunicationIdentityClient communicationIdentityClient = new CommunicationIdentityClientBuilder()
.connectionString(connectionString)
.buildClient();
CommunicationUserIdentifier user = communicationIdentityClient.createUser();
System.out.println("User id: " + user.getId());
CommunicationRelayConfiguration config = communicationRelayClient.getRelayConfiguration(user);
System.out.println("Expires on:" + config.getExpiresOn());
List<CommunicationIceServer> iceServers = config.getIceServers();
for (CommunicationIceServer iceS : iceServers) {
System.out.println("URLS: " + iceS.getUrls());
System.out.println("Username: " + iceS.getUsername());
System.out.println("Credential: " + iceS.getCredential());
}
Run the code
Navigate to the directory containing the pom.xml file and compile the project by using the following mvn command.
mvn compile
Then, build the package.
mvn package
Run the following mvn command to execute the app.
Navigate to the directory containing the pom.xml file and compile the project by using the following mvn command.
mvn compile
Then, build the package.
mvn package
Run the following mvn command to execute the app.
mvn exec:java -Dexec.mainClass="com.communication.quickstart.App" -Dexec.cleanupDaemonThreads=false
Clean up resources
If you want to clean up and remove a Communication Services resource, you can delete the resource or resource group. Deleting the resource group also deletes any other resources associated with it. Learn more about cleaning up resources.
Povratne informacije
Pošalјite i prikažite povratne informacije za