快速入門:使用 Microsoft Entra 識別碼進行驗證

使用 Microsoft Entra ID 開始使用 Azure 通訊服務。 通訊服務身分識別和SMS SDK支援 Microsoft Entra 驗證。

本快速入門說明如何授權從支援 Active Directory 的 Azure 環境存取身分識別和 SMS SDK。 它也描述如何藉由為工作建立服務主體,在開發環境中測試程序代碼。

必要條件

其他必要條件

建立

針對其他 Azure 資源使用 Active Directory 時,您應該使用受控識別。 若要了解如何啟用 Azure 資源的受控識別,請參閱下列其中一篇文章:

在開發環境中驗證已註冊的應用程式

如果您的開發環境不支援透過網頁瀏覽器單一登錄或登入,您可以使用已註冊的應用程式從開發環境進行驗證。

建立 Microsoft Entra 已註冊的應用程式

若要從 Azure CLI 建立已註冊的應用程式,您必須登入您想要進行作業的 Azure 帳戶。 若要這樣做,您可以使用 az login 命令,並在瀏覽器中輸入您的認證。 從 CLI 登入 Azure 帳戶之後,我們可以呼叫 az ad sp create-for-rbac 命令來建立已註冊的應用程式和服務主體。

下列範例會使用 Azure CLI 來建立新的已註冊應用程式:

az ad sp create-for-rbac --name <application-name> --role Contributor --scopes /subscriptions/<subscription-id>

此命令 az ad sp create-for-rbac 會傳回 JSON 格式的服務主體屬性清單。 複製這些值,讓您可以在下一個步驟中用來建立必要的環境變數。

{
    "appId": "generated-app-ID",
    "displayName": "service-principal-name",
    "name": "http://service-principal-uri",
    "password": "generated-password",
    "tenant": "tenant-ID"
}

重要

Azure 角色指派可能需要數分鐘的時間傳播。

設定環境變數

Azure 身分識別 SDK 會從運行時間的三個環境變數讀取值,以驗證應用程式。 下表說明每個環境變數的設定值。

環境變數
AZURE_CLIENT_ID appId 來自產生的 JSON 值
AZURE_TENANT_ID tenant 來自產生的 JSON 值
AZURE_CLIENT_SECRET password 來自產生的 JSON 值

重要

設定環境變數之後,請關閉並重新開啟主控台視窗。 如果您使用 Visual Studio 或其他開發環境,您可能需要重新啟動它,才能註冊新的環境變數。

設定這些變數之後,您應該能夠使用程式代碼中的 DefaultAzureCredential 物件向您選擇的服務用戶端進行驗證。

設定

建立新的 C# 應用程式

在主控台視窗中 (例如 cmd、PowerShell 或 Bash),使用 dotnet new 命令建立名為 ActiveDirectoryQuickstart 的新主控台應用程式。 此命令會建立簡單的 "Hello World" C# 專案,內含單一原始程式檔:Program.cs

dotnet new console -o ActiveDirectoryAuthenticationQuickstart

將您的目錄變更為新建立的應用程式資料夾,然後使用 dotnet build 命令來編譯您的應用程式。

cd ActiveDirectoryAuthenticationQuickstart
dotnet build

安裝 SDK 套件

dotnet add package Azure.Communication.Identity
dotnet add package Azure.Communication.Sms
dotnet add package Azure.Identity

使用 SDK 套件

將下列using指示詞新增至 Program.cs ,以使用 Azure 身分識別和 Azure 儲存體 SDK。

using Azure.Identity;
using Azure.Communication.Identity;
using Azure.Communication.Sms;
using Azure.Core;
using Azure;

建立 DefaultAzureCredential

我們將在本快速入門中使用 DefaultAzureCredential 。 此認證適用於生產和開發環境。 因為每個作業都需要它,讓我們在 Program.cs 類別內建立它。 將下列內容新增至檔案頂端。

private DefaultAzureCredential credential = new DefaultAzureCredential();

使用服務主體發出令牌

現在,我們將新增使用已建立認證的程序代碼,以發出 VoIP 存取令牌。 我們稍後會呼叫此程序代碼。

public AccessToken CreateIdentityAndGetTokenAsync(Uri resourceEndpoint)
{
    var client = new CommunicationIdentityClient(resourceEndpoint, this.credential);
    var result = client.CreateUserAndToken(scopes: new[] { CommunicationTokenScope.VoIP });
    var (user, token) = response.Value;
    return token;
}

使用服務主體傳送SMS

作為使用服務主體的另一個範例,我們將新增此程序代碼,此程式代碼會使用相同的認證來傳送 SMS:

public SmsSendResult SendSms(Uri resourceEndpoint, string from, string to, string message)
{
    SmsClient smsClient = new SmsClient(resourceEndpoint, this.credential);
    SmsSendResult sendResult = smsClient.Send(
            from: from,
            to: to,
            message: message,
            new SmsSendOptions(enableDeliveryReport: true) // optional
        );

    return sendResult;
}

撰寫Main方法

您應該 Program.cs 已經有Main方法,讓我們新增一些程式代碼,以呼叫我們先前建立的程式代碼來示範服務主體的使用:

static void Main(string[] args)
{
    // You can find your endpoint and access key from your resource in the Azure portal
    // e.g. "https://<RESOURCE_NAME>.communication.azure.com";
    Uri endpoint = new("https://<RESOURCENAME>.communication.azure.com/");

    // We need an instance of the program class to use within this method.
    Program instance = new();

    Console.WriteLine("Retrieving new Access Token, using Service Principals");
    AccessToken response = instance.CreateIdentityAndGetTokenAsync(endpoint);
    Console.WriteLine($"Retrieved Access Token: {response.Token}");

    Console.WriteLine("Sending SMS using Service Principals");

    // You will need a phone number from your resource to send an SMS.
    SmsSendResult result = instance.SendSms(endpoint, "<Your Azure Communication Services Phone Number>", "<The Phone Number you'd like to send the SMS to.>", "Hello from using Service Principals");
    Console.WriteLine($"Sms id: {result.MessageId}");
    Console.WriteLine($"Send Result Successful: {result.Successful}");
}

您的最終 Program.cs 檔案看起來應該像這樣:

class Program
     {
          private DefaultAzureCredential credential = new DefaultAzureCredential();
          static void Main(string[] args)
          {
               // You can find your endpoint and access key from your resource in the Azure portal
               // e.g. "https://<RESOURCE_NAME>.communication.azure.com";
               Uri endpoint = new("https://acstestingrifox.communication.azure.com/");

               // We need an instance of the program class to use within this method.
               Program instance = new();

               Console.WriteLine("Retrieving new Access Token, using Service Principals");
               AccessToken response = instance.CreateIdentityAndGetTokenAsync(endpoint);
               Console.WriteLine($"Retrieved Access Token: {response.Token}");

               Console.WriteLine("Sending SMS using Service Principals");

               // You will need a phone number from your resource to send an SMS.
               SmsSendResult result = instance.SendSms(endpoint, "<Your Azure Communication Services Phone Number>", "<The Phone Number you'd like to send the SMS to.>", "Hello from Service Principals");
               Console.WriteLine($"Sms id: {result.MessageId}");
               Console.WriteLine($"Send Result Successful: {result.Successful}");
          }
          public AccessToken CreateIdentityAndGetTokenAsync(Uri resourceEndpoint)
          {
               var client = new CommunicationIdentityClient(resourceEndpoint, this.credential);
               var result = client.CreateUserAndToken(scopes: new[] { CommunicationTokenScope.VoIP });
               var (user, token) = response.Value;
               return token;
          }
          public SmsSendResult SendSms(Uri resourceEndpoint, string from, string to, string message)
          {
               SmsClient smsClient = new SmsClient(resourceEndpoint, this.credential);
               SmsSendResult sendResult = smsClient.Send(
                    from: from,
                    to: to,
                    message: message,
                    new SmsSendOptions(enableDeliveryReport: true) // optional
               );

               return sendResult;
          }
    }

執行程式

您現在應該能夠從應用程式資料夾使用 dotnet run 來執行應用程式。 輸出應該如以下所示:

Retrieving new Access Token, using Service Principals
Retrieved Access Token: ey....
Sending SMS using Service Principals
Sms id: Outgoing_..._noam
Send Result Successful: True

設定

建立新的 Node.js 應用程式

開啟終端機或命令視窗,為您的應用程式建立新的目錄,然後流覽至該目錄。

mkdir active-directory-authentication-quickstart && cd active-directory-authentication-quickstart

執行 npm init -y 以使用預設設定建立 package.json 檔案。

npm init -y

安裝 SDK 套件

npm install @azure/communication-identity
npm install @azure/communication-common
npm install @azure/communication-sms
npm install @azure/identity

建立新檔案

使用文字編輯器開啟新的檔案,並將它儲存為 index.js,我們會將此程式代碼放在這個檔案中。

使用 SDK 套件

將下列require指示詞新增至 頂端index.js,以使用 Azure 身分識別和 Azure 儲存體 SDK。

const { DefaultAzureCredential } = require("@azure/identity");
const { CommunicationIdentityClient, CommunicationUserToken } = require("@azure/communication-identity");
const { SmsClient, SmsSendRequest } = require("@azure/communication-sms");

建立 DefaultAzureCredential

我們將在本快速入門中使用 DefaultAzureCredential 。 此認證適用於生產和開發環境。 因為每個作業都需要它,讓我們在檔案 index.js 頂端建立它。

    const credential = new DefaultAzureCredential();

建立身分識別,並使用服務主體發出令牌

接下來,我們將撰寫函式來建立新的身分識別併發出此身分識別的令牌,稍後我們將使用此函式來測試服務主體設定。

async function createIdentityAndIssueToken(resourceEndpoint) {
    const client = new CommunicationIdentityClient(resourceEndpoint, credential);
    return await client.createUserAndToken(["chat"]);
}

使用服務主體傳送SMS

現在,讓我們撰寫使用服務主體傳送SMS的函式:

async function sendSms(resourceEndpoint, fromNumber, toNumber, message) {
    const smsClient = new SmsClient(resourceEndpoint, credential);
    const sendRequest = {
        from: fromNumber,
        to: [toNumber],
        message: message
    };
    return await smsClient.send(
        sendRequest,
        {} //Optional SendOptions
    );
}

撰寫main函式

建立函式后,我們現在可以撰寫main函式來呼叫它們,並示範服務主體的使用:

async function main() {
    // You can find your endpoint and access key from your resource in the Azure portal
    // e.g. "https://<RESOURCE_NAME>.communication.azure.com";
    const endpoint = "https://<RESOURCE_NAME>.communication.azure.com/"

    
    console.log("Retrieving new Access Token, using Service Principals");
    const result = await createIdentityAndIssueToken(endpoint);
    console.log(`Retrieved Access Token: ${result.token}`);

    console.log("Sending SMS using Service Principals");

    // You will need a phone number from your resource to send an SMS.
    const smsResult = await sendSms(endpoint, "<FROM NUMBER>", "<TO NUMBER>", "Hello from Service Principals");
    console.log(`SMS ID: ${smsResult[0].messageId}`);
    console.log(`Send Result Successful: ${smsResult[0].successful}`);
}

main();

最終 index.js 檔案看起來應該像這樣:

const { DefaultAzureCredential } = require("@azure/identity");
const { CommunicationIdentityClient, CommunicationUserToken } = require("@azure/communication-identity");
const { SmsClient, SmsSendRequest } = require("@azure/communication-sms");

const credential = new DefaultAzureCredential();

async function createIdentityAndIssueToken(resourceEndpoint) {
    const client = new CommunicationIdentityClient(resourceEndpoint, credential);
    return await client.createUserAndToken(["chat"]);
}

async function sendSms(resourceEndpoint, fromNumber, toNumber, message) {
    const smsClient = new SmsClient(resourceEndpoint, credential);
    const sendRequest = {
        from: fromNumber,
        to: [toNumber],
        message: message
    };
    return await smsClient.send(
        sendRequest,
        {} //Optional SendOptions
    );
}

async function main() {
    // You can find your endpoint and access key from your resource in the Azure portal
    // e.g. "https://<RESOURCE_NAME>.communication.azure.com";
    const endpoint = "https://<RESOURCE_NAME>.communication.azure.com/"

    
    console.log("Retrieving new Access Token, using Service Principals");
    const result = await createIdentityAndIssueToken(endpoint);
    console.log(`Retrieved Access Token: ${result.token}`);

    console.log("Sending SMS using Service Principals");

    // You will need a phone number from your resource to send an SMS.
    const smsResult = await sendSms(endpoint, "<FROM NUMBER>", "<TO NUMBER>", "Hello from Service Principals");
    console.log(`SMS ID: ${smsResult[0].messageId}`);
    console.log(`Send Result Successful: ${smsResult[0].successful}`);
}

main();

執行程式

完成一切之後,您可以從專案的目錄輸入 node index.js 來執行檔案。 如果一切順利,您應該會看到類似下面的內容。

    $ node index.js
    Retrieving new Access Token, using Service Principals
    Retrieved Access Token: ey...Q
    Sending SMS using Service Principals
    SMS ID: Outgoing_2021040602194...._noam
    Send Result Successful: true

Java 的其他必要條件

針對 Java,您也需要:

設定

建立新的 Java 應用程式

開啟終端機或命令視窗。 流覽至您要建立 Java 應用程式的目錄。 執行下列命令,從 maven-archetype-quickstart 範本產生 Java 專案。

mvn archetype:generate -DgroupId=com.communication.quickstart -DartifactId=communication-quickstart -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=false

您會發現『generate』 工作已建立與 相同名稱的 artifactId目錄。 在此目錄下,src/main/java 目錄包含專案原始程式碼、 src/test/java directory 包含測試來源,而 pom.xml 檔案是專案的 Project 物件模型或 POM。

Install the package

在文字編輯器中開啟 pom.xml 檔案。 將下列相依性元素加入至相依性群組。

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-communication-identity</artifactId>
    <version>[1.4.0,)</version>
</dependency>
<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-communication-sms</artifactId>
    <version>1.0.0</version>
</dependency>
<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-identity</artifactId>
    <version>1.2.3</version>
</dependency>

使用 SDK 套件

將下列 import 指示詞新增至您的程序代碼,以使用 Azure 身分識別和 Azure 通訊 SDK。

import com.azure.communication.common.*;
import com.azure.communication.identity.*;
import com.azure.communication.identity.models.*;
import com.azure.communication.sms.*;
import com.azure.communication.sms.models.*;
import com.azure.core.credential.*;
import com.azure.identity.*;

import java.util.*;

建立 DefaultAzureCredential

我們將在本快速入門中使用 DefaultAzureCredential 。 此認證適用於生產和開發環境。 因為每個作業都需要它,讓我們在 App.java 類別內建立它。 將下列內容新增至 類別頂 App.java 端。

private TokenCredential credential = new DefaultAzureCredentialBuilder().build();

使用服務主體發出令牌

現在,我們將新增使用已建立認證的程序代碼,以發出 VoIP 存取令牌。 我們稍後會呼叫此程序代碼;

    public AccessToken createIdentityAndGetTokenAsync(String endpoint) {
          CommunicationIdentityClient communicationIdentityClient = new CommunicationIdentityClientBuilder()
                    .endpoint(endpoint)
                    .credential(this.credential)
                    .buildClient();

          CommunicationUserIdentifierAndToken result =  communicationIdentityClient.createUserAndToken(new ArrayList<>(Arrays.asList(CommunicationTokenScope.CHAT)));
          return result.getUserToken();
    }

使用服務主體傳送SMS

作為使用服務主體的另一個範例,我們將新增此程序代碼,此程式代碼會使用相同的認證來傳送 SMS:

     public SmsSendResult sendSms(String endpoint, String from, String to, String message) {
          SmsClient smsClient = new SmsClientBuilder()
                    .endpoint(endpoint)
                    .credential(this.credential)
                    .buildClient();

          // Send the message and check the response for a message id
          return smsClient.send(from, to, message);
     }

撰寫Main方法

您應該 App.java 已經有Main方法,讓我們新增一些程式代碼,以呼叫我們先前建立的程式代碼來示範服務主體的使用:

    public static void main(String[] args) {
          App instance = new App();
          // You can find your endpoint and access key from your resource in the Azure portal
          // e.g. "https://<RESOURCE_NAME>.communication.azure.com";
          String endpoint = "https://<RESOURCE_NAME>.communication.azure.com/";

          System.out.println("Retrieving new Access Token, using Service Principals");
          AccessToken token = instance.createIdentityAndGetTokenAsync(endpoint);
          System.out.println("Retrieved Access Token: "+ token.getToken());

          System.out.println("Sending SMS using Service Principals");
          // You will need a phone number from your resource to send an SMS.
          SmsSendResult result = instance.sendSms(endpoint, "<FROM NUMBER>", "<TO NUMBER>", "Hello from Service Principals");
          System.out.println("Sms id: "+ result.getMessageId());
          System.out.println("Send Result Successful: "+ result.isSuccessful());
    }

您的決賽 App.java 看起來應該像這樣:

package com.communication.quickstart;

import com.azure.communication.common.*;
import com.azure.communication.identity.*;
import com.azure.communication.identity.models.*;
import com.azure.communication.sms.*;
import com.azure.communication.sms.models.*;
import com.azure.core.credential.*;
import com.azure.identity.*;

import java.util.*;

public class App 
{

    private TokenCredential credential = new DefaultAzureCredentialBuilder().build();

    public SmsSendResult sendSms(String endpoint, String from, String to, String message) {
          SmsClient smsClient = new SmsClientBuilder()
               .endpoint(endpoint)
               .credential(this.credential)
               .buildClient();

          // Send the message and check the response for a message id
          return smsClient.send(from, to, message);
    }
    
    public AccessToken createIdentityAndGetTokenAsync(String endpoint) {
          CommunicationIdentityClient communicationIdentityClient = new CommunicationIdentityClientBuilder()
                    .endpoint(endpoint)
                    .credential(this.credential)
                    .buildClient();

          CommunicationUserIdentifierAndToken result =  communicationIdentityClient.createUserAndToken(new ArrayList<>(Arrays.asList(CommunicationTokenScope.CHAT)));
          return result.getUserToken();
    }

    public static void main(String[] args) {
          App instance = new App();
          // You can find your endpoint and access key from your resource in the Azure portal
          // e.g. "https://<RESOURCE_NAME>.communication.azure.com";
          String endpoint = "https://<RESOURCE_NAME>.communication.azure.com/";

          System.out.println("Retrieving new Access Token, using Service Principals");
          AccessToken token = instance.createIdentityAndGetTokenAsync(endpoint);
          System.out.println("Retrieved Access Token: "+ token.getToken());

          System.out.println("Sending SMS using Service Principals");
          // You will need a phone number from your resource to send an SMS.
          SmsSendResult result = instance.sendSms(endpoint, "<FROM NUMBER>", "<TO NUMBER>", "Hello from Service Principals");
          System.out.println("Sms id: "+ result.getMessageId());
          System.out.println("Send Result Successful: "+ result.isSuccessful());
    }
}

執行程式碼

流覽至包含pom.xml檔案的目錄,並使用下列mvn命令編譯專案。

mvn compile

接著,建置封裝。

mvn package

執行下列 mvn 命令以執行應用程式。

mvn exec:java -Dexec.mainClass="com.communication.quickstart.App" -Dexec.cleanupDaemonThreads=false

最終輸出應該如下所示:

Retrieving new Access Token, using Service Principals
Retrieved Access Token: ey..A
Sending SMS using using Service Principals
Sms id: Outgoing_202104...33f8ae1f_noam
Send Result Successful: true

設定

建立新的 Python 應用程式

開啟終端機或命令視窗,為您的應用程式建立新的目錄,然後流覽至該目錄。

mkdir active-directory-authentication-quickstart && cd active-directory-authentication-quickstart

安裝 SDK 套件

pip install azure-identity
pip install azure-communication-identity
pip install azure-communication-sms

建立新檔案

開啟並儲存名為 的新檔案, authentication.py我們會將此程式代碼放在此檔案中。

使用 SDK 套件

將下列 import 語句新增至檔案頂端,以使用我們安裝的 SDK。

from azure.identity import DefaultAzureCredential
from azure.communication.identity import CommunicationIdentityClient
from azure.communication.sms import SmsClient

建立 DefaultAzureCredential

我們將使用 DefaultAzureCredential。 此認證適用於生產和開發環境。 在本快速入門中,我們將使用它,我們會在檔案頂端建立它。

     credential = DefaultAzureCredential()

建立身分識別,並使用服務主體發出令牌

現在,我們將新增使用已建立認證的程序代碼,以發出 VoIP 存取令牌。 我們稍後會在下列專案上呼叫此程序代碼:

def create_identity_and_get_token(resource_endpoint):
     client = CommunicationIdentityClient(resource_endpoint, credential)
     user, token_response = client.create_user_and_token(scopes=["voip"])

     return token_response

使用服務主體傳送SMS

作為使用服務主體的另一個範例,我們將新增此程序代碼,此程式代碼會使用相同的認證來傳送 SMS:

def send_sms(resource_endpoint, from_phone_number, to_phone_number, message_content):
     sms_client = SmsClient(resource_endpoint, credential)

     sms_client.send(
          from_=from_phone_number,
          to_=[to_phone_number],
          message=message_content,
          enable_delivery_report=True  # optional property
     )

撰寫我們的主要程序代碼

建立函式后,我們現在可以撰寫主要程序代碼,以呼叫先前撰寫的函式。

# You can find your endpoint and access key from your resource in the Azure portal
# e.g. "https://<RESOURCE_NAME>.communication.azure.com";
endpoint = "https://<RESOURCE_NAME>.communication.azure.com/"

print("Retrieving new Access Token, using Service Principals");
result = create_identity_and_get_token(endpoint);
print(f'Retrieved Access Token: {result.token}');

print("Sending SMS using Service Principals");

# You will need a phone number from your resource to send an SMS.
sms_result = send_sms(endpoint, "<FROM_NUMBER>", "<TO_NUMBER>", "Hello from Service Principals");
print(f'SMS ID: {sms_result[0].message_id}');
print(f'Send Result Successful: {sms_result[0].successful}');

最終 authentication.py 檔案看起來應該像這樣:

from azure.identity import DefaultAzureCredential
from azure.communication.identity import CommunicationIdentityClient
from azure.communication.sms import SmsClient

credential = DefaultAzureCredential()

def create_identity_and_get_token(resource_endpoint):
     client = CommunicationIdentityClient(resource_endpoint, credential)
     user, token_response = client.create_user_and_token(scopes=["voip"])

     return token_response

def send_sms(resource_endpoint, from_phone_number, to_phone_number, message_content):
     sms_client = SmsClient(resource_endpoint, credential)

     response = sms_client.send(
          from_=from_phone_number,
          to=[to_phone_number],
          message=message_content,
          enable_delivery_report=True  # optional property
     )
     return response

# You can find your endpoint and access key from your resource in the Azure portal
# e.g. "https://<RESOURCE_NAME>.communication.azure.com";
endpoint = "https://<RESOURCE_NAME>.communication.azure.com/"

print("Retrieving new Access Token, using Service Principals");
result = create_identity_and_get_token(endpoint);
print(f'Retrieved Access Token: {result.token}');

print("Sending SMS using Service Principals");

# You will need a phone number from your resource to send an SMS.
sms_result = send_sms(endpoint, "<FROM_NUMBER>", "<TO_NUMBER>", "Hello from Service Principals");
print(f'SMS ID: {sms_result[0].message_id}');
print(f'Send Result Successful: {sms_result[0].successful}');

執行程式

完成一切之後,您可以從專案的目錄輸入 python authentication.py 來執行檔案。 如果一切順利,您應該會看到類似下面的內容。

    $ python authentication.py
    Retrieving new Access Token, using Service Principals
    Retrieved Access Token: ey...Q
    Sending SMS using using Service Principals
    SMS ID: Outgoing_2021040602194...._noam
    Send Result Successful: true

下一步