Edit

Share via


Quickstart: Set up and obtain access tokens for Microsoft Entra ID users

Important

This feature of Azure Communication Services is currently in preview. Features in preview are publicly available and can be used by all new and existing Microsoft customers.

Preview APIs and SDKs are provided without a service-level agreement. We recommend that you don't use them for production workloads. Certain features might not be supported or capabilities might be constrained.

For more information, see Supplemental Terms of Use for Microsoft Azure Previews.

This quickstart demonstrates how to use the Communication Services Common SDK along with Azure Identity SDK in a console application to authenticate a Microsoft Entra ID user and obtain an Azure Communication Services access token. The resulting Azure Communication Services access token allows you to integrate calling and chat features using the Communication Services Calling and Chat SDKs.

Prerequisites

Introduction

Your application can support users from either the same tenant or different tenants. In this quickstart, you'll explore a multitenant scenario involving users, developers, and administrators from the fictional companies Contoso and Fabrikam. In this example, Contoso is providing a software as a service (SaaS) solution for Fabrikam.

The following sections walk you through the steps required for administrators, developers, and users. The included diagrams illustrate the multitenant scenario. If you're working in a single-tenant environment, complete all steps for both Contoso and Fabrikam within the same tenant.

Administrator actions

The Administrator role has extended permissions in Microsoft Entra ID. Members of this role can set up and manage resources. In the following diagram, you can see all actions that have to be executed by Administrators.

Diagram that shows administrator actions to enable Azure Communication Services support for Microsoft Entra ID users.

  1. The Contoso Administrator creates a service principal for Communication Services Clients application in Contoso Microsoft Entra ID tenant. This step is required to allow the Contoso application to access Communication Services Clients application API permissions.
  2. The Contoso Administrator creates or selects an existing application in Microsoft Entra ID. The property Supported account types defines whether users from various tenants can authenticate to the application. The property Redirect URI redirects a successful authentication request to the Contoso client application.
  3. The Contoso Administrator adds required API permissions from Communication Services Clients application. For the all list of the permissions, see Access tokens with Microsoft Entra ID.
  4. The Contoso Administrator creates or selects existing communication services. The Contoso Administrator grants Fabrikam Entra ID users access to Contoso Azure Communication Services resource. Azure Communication Services Common SDK will be used for Microsoft Entra ID user authentication and in the background seamlessly obtain an Azure Communication Services access token for Microsoft Entra ID user.
  5. The Fabrikam Administrator grants admin consent for the required Communication Services Clients application API permissions to the Contoso application.

Step 1: Create a service principal for Azure Communication Services Clients application

To enable the Contoso application to access Azure Communication Services Clients application API permissions, the Contoso Administrator must create a service principal for Azure Communication Services Clients application in the Contoso Microsoft Entra ID tenant. The Contoso Administrator can create a service principal in Contoso tenant by one of the following methods:

POST https://graph.microsoft.com/v1.0/servicePrincipals
Content-Type: application/json

{
  "appId": "2a04943b-b6a7-4f65-8786-2bb6131b59f6"
}

This request can also be executed in Graph Explorer. Make sure to include your full tenant domain in the URL https://developer.microsoft.com/graph/graph-explorer?tenant={tenant domain}, sign in, and provide consent for Application.ReadWrite.All permission.

  • Use the Azure CLI to run the following command:
az ad sp create --id 2a04943b-b6a7-4f65-8786-2bb6131b59f6

Step 2: Create a Microsoft Entra application registration or select a Microsoft Entra application

Users must be authenticated against Microsoft Entra applications with Azure Communication Services Clients application API permissions. If you don't have an existing application that you want to use for this quickstart, you can create a new application registration.

The following application settings influence the experience:

  • The Supported account types property defines whether the application is single tenant ("Accounts in this organizational directory only") or multitenant ("Accounts in any organizational directory"). For this scenario, you can use multitenant.
  • Redirect URI defines the URI where the authentication request is redirected after authentication.

For more detailed information, see Register an application with the Microsoft identity platform.

Step 3: Add Azure Communication Services Clients permissions in the application

The application must declare Azure Communication Services Clients to have access to Azure Communication Services capabilities. Microsoft Entra ID user would be requesting a Microsoft Entra user token with these permissions.

  1. Navigate to your Microsoft Entra app in the Azure portal and select API permissions
  2. Select Add Permissions
  3. In the Add Permissions menu, select APIs my organization uses
  4. Search for and select Azure Communication Services Clients
  5. Select the permissions VoIP and Chat, then select Add permissions
  6. Grant admin consent for all delegated permissions.

Diagram that shows how to add Communication Services Clients permissions to the Microsoft Entra application created in previous step.

Step 4: Create or select a Communication Services resource and grant Entra ID users access to it

The Azure Communication Services resource is used to authenticate all requests from Microsoft Entra ID users and to grant them access to the resource.

If you want to create a new Communication Services resource, see Create and manage Communication Services resources.

The Contoso administrator can provide Fabrikam Entra ID users with access to the Contoso Azure Communication Services resource through the Azure portal or by using the Entra ID Assignment REST API.

Currently, assigning access to Azure Communication Services resources via the Azure portal is a preview feature. To access it, launch the Azure portal using this URL - Azure portal with Access Assignment Preview Enabled. In the Azure portal follow these steps:

  1. Navigate to your Communication Services resource.
  2. In the left pane, select User access for Entra ID under the Settings group.
  3. Click the Add button to provide access to an Entra user, group, or entire tenant.
  4. In the Principal type select the correct value. In this scenario Contoso Admin provides access for a group from Fabrikam tenant and chooses Group.
  5. In the Object ID field, enter the object ID of the group from Fabrikam Microsoft Entra tenant.
  6. In the Tenant ID field, enter the tenant ID of the Fabrikam Microsoft Entra tenant.
  7. In the Client ID field, enter the client ID of Contoso application from step 2.
  8. Click Save and exit to apply the changes.

Screenshot of providing Entra ID users with access to the Azure Communication Services resource through the Azure portal.

Microsoft Entra tenant can be configured, to require Microsoft Entra administrator consent for Azure Communication Services Clients API permissions of the application. In such a case, the Microsoft Entra Administrator must grant permissions to the Contoso application for Azure Communication Services Clients API permissions. The Fabrikam Microsoft Entra Administrator provides consent via a unique URL.

The following roles can provide consent on behalf of a company:

  • Global admin
  • Application admin
  • Cloud application admin

If you want to check roles in Azure portal, see List Azure role assignments.

To construct an Administrator consent URL, the Fabrikam Microsoft Entra Administrator does the following steps:

  1. In the URL https://login.microsoftonline.com/{Tenant_ID}/adminconsent?client_id={Application_ID}, the Administrator replaces {Tenant_ID} with the Fabrikam Tenant ID, and replaces {Application_ID} with the Contoso Application ID.
  2. The Administrator logs in and grants permissions on behalf of the organization.

The service principal of the Contoso application in the Fabrikam tenant is created if consent is granted. The Fabrikam Administrator can review the consent in Microsoft Entra ID by doing the following steps:

  1. Sign in to the Azure portal as an administrator.
  2. Go to Microsoft Entra ID.
  3. On the Enterprise applications pane, set the Application type filter to All applications.
  4. In the field for filtering the applications, enter the name of the Contoso application.
  5. Select Apply.
  6. Select the service principal by using the required name.
  7. Go to the Permissions pane.

You can see that the status of the Communication Services Clients application API permissions is Granted for {Directory_name}.

If you run into the issue "The app is trying to access a service '2a04943b-b6a7-4f65-8786-2bb6131b59f6'(Azure Communication Services Clients) that your organization '{GUID}' lacks a service principal for. You need to create a service principal for your tenant by following the instructions in the Step 1: Create a service principal for Azure Communication Services Clients application.

The group access to Azure Communication Services Clients application should be only provided if the Contoso Administrator provided a group access to the Contoso Azure Communication Services resource in the previous step. For the user or entire tenant access to the Azure Communication Services resource, the Fabrikam Administrator can skip this step.

Group-based assignment requires Microsoft Entra ID P1 or P2 edition. The Fabrikam Administrator can provide access to the group from Fabrikam tenant by using the Microsoft Entra admin center. To provide access to the group, the Fabrikam Administrator does the following steps:

  1. Log in to Microsoft Entra admin center with Global Administrator or Tenant Administrator roles.
  2. Navigate to Identity > Applications > Enterprise applications in the left panel menu.
  3. In the search box, enter Azure Communication Services Clients, and then select the application from the search results.
  4. In the left panel menu, select Users and groups and then select Add user/group.
  5. On the Add Assignment pane, select None Selected under Users and groups.
  6. Search for and select the group that you want to assign to the application.
  7. Click on Select and then select Assign to assign the group to the application.

Diagram that shows how to assign group access to Azure Communication Services Clients application.

Developer actions

The Contoso developer needs to set up the client application to authenticate users. In the client application, the developer creates a credential using Communication Common SDK along with any implementation of the TokenCredential from Azure Identity SDK capable of authenticating users against the Microsoft Entra ID application.

The developer's required actions are shown in following diagram:

Diagram of developer actions to enable Azure Communication Services support for Microsoft Entra ID users.

  1. The Contoso developer initializes any implementation of TokenCredential from Azure Identity SDK which is capable of obtaining a Microsoft Entra user token for the application that was created earlier by the Contoso Administrator.
  2. The Contoso developer initializes AzureCommunicationTokenCredential from Communication Services Common SDK with TokenCredential created in the step 1. The AzureCommunicationTokenCredential obtains an Azure Communication Services access token for Microsoft Entra ID user seamlessly in the background.

Note

The following sections describe how to create AzureCommunicationTokenCredential.

Set up prerequisites

Final code

Find the finalized code for this quickstart on GitHub.

Set up

Create a new C# application

In a console window (such as cmd, PowerShell, or Bash), use the dotnet new command to create a new console app with the name EntraIdUsersSupportQuickstart. This command creates a simple "Hello World" C# project with a single source file: Program.cs.

dotnet new console -o EntraIdUsersSupportQuickstart

Change your directory to the newly created app folder and use the dotnet build command to compile your application.

cd EntraIdUsersSupportQuickstart
dotnet build

Install the package

While still in the application directory, install the Azure Identity and Azure Communication Services Common library for .NET package by using the dotnet add package command. The Azure Communication Services Common SDK version should be 1.4.0 or later.

dotnet add package Azure.Identity
dotnet add package Azure.Communication.Common

Implement the credential flow

From the project directory:

  1. Open Program.cs file in a text editor
  2. Replace the contents of Program.cs with the following code:
using Azure.Communication;
using Azure.Identity;

namespace EntraIdUsersSupportQuickstart
{
    class Program
    {
        static async Task Main(string[] args)
        {
            Console.WriteLine("Azure Communication Services - Obtain Access Token for Entra ID User Quickstart");

            // Quickstart code goes here
        }
    }
}

Step 1: Initialize implementation of TokenCredential from Azure Identity SDK

The first step in obtaining Communication Services access token for Entra ID user is getting an Entra ID access token for your Entra ID user by using Azure.Identity SDK. The code below retrieves the Contoso Entra client ID and the Fabrikam tenant ID from environment variables named ENTRA_CLIENT_ID and ENTRA_TENANT_ID. To enable authentication for users across multiple tenants, initialize the InteractiveBrowserCredential class with the authority set to https://login.microsoftonline.com/organizations. For more information, see Authority.

// This code demonstrates how to fetch your Microsoft Entra client ID and tenant ID from environment variables.
string clientId = Environment.GetEnvironmentVariable("ENTRA_CLIENT_ID");
string tenantId = Environment.GetEnvironmentVariable("ENTRA_TENANT_ID");

//Initialize InteractiveBrowserCredential for use with CommunicationTokenCredential.
var options = new InteractiveBrowserCredentialOptions
{
    TenantId = tenantId,
    ClientId = clientId,
};
var entraTokenCredential = new InteractiveBrowserCredential(options);

Step 2: Initialize CommunicationTokenCredential

Instantiate a CommunicationTokenCredential with the TokenCredential created above and your Communication Services resource endpoint URI. The code below retrieves the endpoint for the resource from an environment variable named COMMUNICATION_SERVICES_RESOURCE_ENDPOINT.

Add the following code to the Main method:

// This code demonstrates how to fetch your Azure Communication Services resource endpoint URI
// from an environment variable.
string resourceEndpoint = Environment.GetEnvironmentVariable("COMMUNICATION_SERVICES_RESOURCE_ENDPOINT");

// Set up CommunicationTokenCredential to request a Communication Services access token for a Microsoft Entra ID user.
var entraTokenCredentialOptions = new EntraCommunicationTokenCredentialOptions(
    resourceEndpoint: resourceEndpoint,
    entraTokenCredential: entraTokenCredential)
{
    Scopes = new[] { "https://communication.azure.com/clients/VoIP" }
};

var credential = new CommunicationTokenCredential(entraTokenCredentialOptions);

Providing scopes is optional. When not specified, the https://communication.azure.com/clients/.default scope is automatically used, requesting all API permissions for Communication Services Clients that have been registered on the client application.

Step 3: Obtain Azure Communication Services access token for Microsoft Entra ID user

Use the GetTokenAsync method to obtain an access token for the Entra ID user. The CommunicationTokenCredential can be used with the Azure Communication Services SDKs.

// To obtain a Communication Services access token for Microsoft Entra ID call GetTokenAsync() method.
var accessToken = await credential.GetTokenAsync();
Console.WriteLine($"Token: {accessToken.Token}");

Run the code

Run the application from your application directory with the dotnet run command.

dotnet run

Set up prerequisites

Final code

Find the finalized code for this quickstart on GitHub.

Set 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 entra-id-users-support-quickstart && cd entra-id-users-support-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 Identity and Azure Communication Services Common SDKs for JavaScript. The Azure Communication Services Common SDK version should be 2.4.0 or later.

npm install @azure/communication-common --save
npm install @azure/identity --save
npm install react react-dom --save
npm install vite --save

The --save option lists the library as a dependency in your package.json file.

Add these scripts to your package.json:

"scripts": {
  "dev": "vite",
  "build": "vite build",
  "preview": "vite preview"
}

Implement the credential flow

In this quickstart, you will create a simple React application that uses the Azure Common SDK to obtain an access token for a Microsoft Entra ID user.

From the project directory:

  1. Create a index.html file with the following content:

    <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8" />
            <title>Entra ID Support Client</title>
        </head>
        <body>
            <div id="root"></div>
            <script type="module" src="/src/main.jsx"></script>
        </body>
    </html>
    
  2. Create a src directory and inside it create a main.jsx file with the following content:

    import React from "react";
    import ReactDOM from "react-dom/client";
    import App from "./App";
    
    ReactDOM.createRoot(document.getElementById("root")).render(<App />);
    
  3. Create a src/App.jsx file with the following content and import the AzureCommunicationTokenCredential and InteractiveBrowserCredential classes from the Azure Communication Common and Azure Identity SDKs, respectively. Also make sure to update the clientId, tenantId, and resourceEndpoint variables with your Microsoft Entra client ID, tenant ID, and Azure Communication Services resource endpoint URI:

    import React, { useState } from "react";
    import { AzureCommunicationTokenCredential } from "@azure/communication-common";    
    import { InteractiveBrowserCredential } from "@azure/identity";
    
    function App() {
        // Set your Microsoft Entra client ID and tenant ID, Azure Communication Services resource endpoint URI.
        const clientId = 'YOUR_ENTRA_CLIENT_ID';
        const tenantId = 'YOUR_ENTRA_TENANT_ID';
        const resourceEndpoint = 'YOUR_COMMUNICATION_SERVICES_RESOURCE_ENDPOINT';
    
        const [accessToken, setAccessToken] = useState("");
        const [error, setError] = useState("");
    
        const handleLogin = async () => {
            try {
                // Quickstart code goes here
                setError("");
            } catch (err) {
                console.error("Error obtaining token:", err);
                setError("Failed to obtain token: " + err.message);
            }
        };
    
        return (
            <div>
                <h2>Obtain Access Token for Entra ID User</h2>
                <button onClick={handleLogin}>Login and Get Access Token</button>
                {accessToken && (
                    <div>
                    <h4>Access Token:</h4>
                    <textarea value={accessToken} readOnly rows={6} cols={60} />
                    </div>
                )}
                {error && <div style={{ color: "red" }}>{error}</div>}
            </div>
        );
    }
    
    export default App;
    

    You can import any implementation of the TokenCredential interface from the Azure Identity SDK for JavaScript to authenticate with Microsoft Entra ID. In this quickstart, we use the InteractiveBrowserCredential class, which is suitable for browser basic authentication scenarios. For a full list of the credentials offered, see Credential Classes.

Step 1: Initialize implementation of TokenCredential from Azure Identity SDK

The first step in obtaining Communication Services access token for Entra ID user is getting an Entra ID access token for your Entra ID user by using Azure Identity SDK. To enable authentication for users across multiple tenants, initialize the InteractiveBrowserCredential class with the authority set to https://login.microsoftonline.com/organizations. For more information, see Authority.

// Initialize InteractiveBrowserCredential for use with AzureCommunicationTokenCredential.
const entraTokenCredential = new InteractiveBrowserCredential({
    tenantId: tenantId,
    clientId: clientId,
    authorityHost: "https://login.microsoftonline.com/organizations",
});

Step 2: Initialize AzureCommunicationTokenCredential

Instantiate a AzureCommunicationTokenCredential with the TokenCredential created above and your Communication Services resource endpoint URI.

// Set up AzureCommunicationTokenCredential to request a Communication Services access token for a Microsoft Entra ID user.
const entraCommunicationTokenCredential = new AzureCommunicationTokenCredential({
    resourceEndpoint: resourceEndpoint,
    tokenCredential: entraTokenCredential,
});

Providing scopes is optional. When not specified, the https://communication.azure.com/clients/.default scope is automatically used, requesting all API permissions for Communication Services Clients that have been registered on the client application.

Step 3: Obtain Azure Communication Services access token for Microsoft Entra ID user

Use the getToken method to obtain an access token for the Entra ID user. The AzureCommunicationTokenCredential can be used with the Azure Communication Services SDKs.

// To obtain a Communication Services access token for Microsoft Entra ID call getToken() function.
let accessToken = await entraCommunicationTokenCredential.getToken();
setAccessToken(accessToken.token);

Run the code

From a console prompt, navigate to the directory entra-id-users-support-quickstart, then execute the following npm command to run the app.

npm run dev 

User actions

The user represents the Fabrikam users of the Contoso application. The user experience is shown in the following diagram:

Diagram of user actions to enable Azure Communication Services support for Microsoft Entra ID users.

  1. The Fabrikam user uses the Contoso client application and is prompted to authenticate.
  2. The Contoso client application uses the Azure Identity SDK to authenticate the user against the Fabrikam Microsoft Entra tenant for the Contoso application with Communication Services Clients permissions. Authentication is redirected to the client application, as defined in the property Redirect URI in the Contoso application.
  3. The Communication Common SDK seamlessly obtains an Azure Communication Services access token for Fabrikam Entra ID user in the background.

Developers can integrate the Communication Services Calling SDK or Chat SDK by providing AzureCommunicationTokenCredential.

Next steps

In this quickstart, you learned how to:

  • Create and configure an application in Microsoft Entra ID.
  • Use Communication Services Common SDK and Azure Identity SDK to integrate Microsoft Entra ID users to Azure Communication Services.

Learn about the following concepts: