次の方法で共有


クイック スタート: Microsoft Entra ID を使用して認証する

Microsoft Entra ID を使用して Azure Communication Services の使用を開始します。 Communication Services ID と SMS SDK は、Microsoft Entra 認証をサポートしています。

このクイック スタートでは、Active Directory をサポートする Azure 環境から ID SDK と SMS SDK へのアクセスを承認する方法について説明します。 また、作業用のサービス プリンシパルを作成して、開発環境でコードをテストする方法についても説明します。

[前提条件]

その他の前提条件

セットアップ

他の Azure リソースに Active Directory を使用する場合は、マネージド ID を使用する必要があります。 Azure リソースのマネージド ID を有効にする方法については、次のいずれかの記事を参照してください。

開発環境で登録済みアプリケーションを認証する

開発環境で Web ブラウザー経由のシングル サインオンまたはログインがサポートされていない場合は、登録済みのアプリケーションを使用して開発環境から認証できます。

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"
}

Von Bedeutung

Azure ロールの割り当てが反映されるまでに数分かかる場合があります。

環境変数の設定

Azure ID SDK では、実行時に 3 つの環境変数から値が読み取られ、アプリケーションが認証されます。 次の表では、各環境変数に設定する値について説明します。

環境変数 価値
AZURE_CLIENT_ID appId 生成された JSON からの値
AZURE_TENANT_ID tenant 生成された JSON からの値
AZURE_CLIENT_SECRET password 生成された JSON からの値

Von Bedeutung

環境変数を設定したら、コンソール ウィンドウを閉じて再び開きます。 Visual Studio または別の開発環境を使用している場合は、新しい環境変数を登録するために再起動が必要になる場合があります。

これらの変数が設定されると、コードで DefaultAzureCredential オブジェクトを使用して、選択したサービス クライアントに対して認証できるようになります。

このクイックスタートの最終的なコードは GitHub にあります

概要

このクイック スタートでは、Azure サービス プリンシパルを介してマネージド ID を使用して Azure Communication Services で認証する方法について説明します。 ボイス オーバー IP (VoIP) 呼び出しのアクセス トークンを発行し、SMS メッセージを送信する例を示します。

セットアップ中

新しい C# アプリケーションを作成する

目標は、クイック スタート コードを実行する新しいコンソール アプリケーションを C# で作成することです。 ターミナル ウィンドウ (コマンド プロンプト、PowerShell、Bash など) を開き、次のコマンドを実行して、 ActiveDirectoryAuthenticationQuickstartという名前の新しいコンソール アプリを作成します。

dotnet new console -o ActiveDirectoryAuthenticationQuickstart

このコマンドを実行すると、単一のソース ファイルである Program.cs を含む、単純な "Hello World" C# プロジェクトが生成されます。

アプリケーションをビルドする

新しく作成したアプリ フォルダーに移動し、 dotnet build コマンドを使用してアプリケーションをコンパイルします。

cd ActiveDirectoryAuthenticationQuickstart
dotnet build

必要な SDK パッケージをインストールする

Azure Communication Services と Azure Identity を操作するには、次の NuGet パッケージをプロジェクトに追加します。

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

Program.cs ファイルを更新する

インストールされている Azure SDK パッケージを使用するには、using ファイルの先頭に次のProgram.cs ディレクティブを含めます。

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();

サービス プリンシパルを使用してトークンを発行する

Program.cs ファイルに次のメソッドを追加します。 この方法では、Azure Communication Services SDK を使用して 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 の送信を示すために、 Program.cs ファイルに次のメソッドを追加します。 この方法では、Azure Communication Services SDK を使用して 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 メソッドを記述する

Main ファイルの Program.cs メソッドに、トークンを発行して SMS を送信するために作成したメソッドを呼び出すコードを追加します。 Mainメソッドは次のようになります。

static void Main(string[] args)
{
    // Replace <RESOURCE_NAME> with your Communication Services resource name,
    // for example: "https://<RESOURCE_NAME>.communication.azure.com".
    Uri endpoint = new("https://<RESOURCENAME>.communication.azure.com/");

    // Create an instance of the Program class to invoke instance methods.
    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");

    // Replace with your Azure Communication Services phone number and the target phone number.
    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)
          {
               // Replace <RESOURCE_NAME> with your Communication Services resource name,
               // for example: "https://<RESOURCE_NAME>.communication.azure.com".
               Uri endpoint = new("https://acstestingrifox.communication.azure.com/");

               // Create an instance of the Program class to invoke instance methods.
               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");

               // Replace with your Azure Communication Services phone number and the target phone number.
               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;
          }
    }

プログラムを実行する

アプリケーションを実行し、アクセス トークンを取得して SMS を送信することを確認します。 ターミナルを開き、アプリケーション ディレクトリに移動して、次のコマンドを実行します。

     dotnet run

コンソール出力は次のように表示されます。

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

このクイックスタートの最終的なコードは GitHub にあります

セットアップ中

新しい 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 ID SDK と Azure Storage 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();

ID を作成し、サービス プリンシパルでトークンを発行する

次に、新しい ID を作成し、この ID のトークンを発行する関数を記述します。後でこれを使用して、サービス プリンシパルのセットアップをテストします。

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: ...
    Send Result Successful: true

Java の追加の前提条件

Java の場合は、次のものが必要になります。

このクイックスタートの最終的なコードは GitHub にあります

セットアップ中

新しい 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 ファイルはプロジェクトのプロジェクト オブジェクト モデル (POM) です。

パッケージをインストールする

テキスト エディターで pom.xml ファイルを開きます。 依存関係のグループに、次の dependency 要素を追加します。

<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 Identity SDK と Azure Communication 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: ...
Send Result Successful: true

このクイックスタートの最終的なコードは GitHub にあります

セットアップ中

新しい Python アプリケーションを作成する

アプリケーションの作業ディレクトリを設定しましょう。 そのためには、ターミナルまたはコマンド ウィンドウを開き、新しいディレクトリを作成して、そこに移動します。

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

SDK パッケージをインストールする

次に、必要な Azure SDK パッケージをインストールする必要があります。 これらのコマンドを実行します。

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

[新しいファイルの作成]

次に、コードを保持するための Python ファイルが必要です。 authentication.pyという名前の新しいファイルをディレクトリ内で開いて保存します。

SDK パッケージを使用する

次の目標は、ID と SMS を操作するために必要な Azure SDK モジュールをインポートすることです。 ファイルの先頭に次のステートメントを追加します。

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

DefaultAzureCredential を作成する

運用環境と開発環境の両方の資格情報を初期化する必要があります。

挿入した行の後にこの行を DefaultAzureCredential として配置します。

     credential = DefaultAzureCredential()

ID を作成し、サービス プリンシパルでトークンを発行する

ID を作成し、Voice over Internet Protocol (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
     )

メイン コードを記述する

これで、ID を作成し、アクセス トークンを取得し、SMS を送信するための関数を実行するために必要なすべてのコード ブロックが用意されました。

関数を呼び出すメイン コードを含めます。

# Retrieve your endpoint and access key from your resource in the Azure portal
# For example: "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");

# Provide a valid phone number from your Azure 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 スクリプトを実行して機能を確認します。 次のコマンドを使用して、プロジェクトのディレクトリからファイルを実行します。

python authentication.py

成功した場合は、次のような出力が表示されます。

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

次のステップ