Szybki start: uwierzytelnianie przy użyciu identyfikatora Entra firmy Microsoft

Rozpocznij pracę z usługami Azure Communication Services przy użyciu identyfikatora Entra firmy Microsoft. Zestawy SDK tożsamości usług komunikacyjnych i sms obsługują uwierzytelnianie firmy Microsoft Entra.

W tym przewodniku Szybki start pokazano, jak autoryzować dostęp do zestawów SDK tożsamości i wiadomości SMS ze środowiska platformy Azure obsługującego usługę Active Directory. W tym artykule opisano również sposób testowania kodu w środowisku projektowym przez utworzenie jednostki usługi dla pracy.

Wymagania wstępne

Dodatkowe wymagania wstępne

Konfigurowanie

W przypadku korzystania z usługi Active Directory dla innych zasobów platformy Azure należy używać tożsamości zarządzanych. Aby dowiedzieć się, jak włączyć tożsamości zarządzane dla zasobów platformy Azure, zobacz jeden z następujących artykułów:

Uwierzytelnianie zarejestrowanej aplikacji w środowisku projektowym

Jeśli środowisko deweloperskie nie obsługuje logowania jednokrotnego ani logowania za pośrednictwem przeglądarki internetowej, możesz użyć zarejestrowanej aplikacji do uwierzytelniania ze środowiska deweloperskiego.

Tworzenie zarejestrowanej aplikacji firmy Microsoft

Aby utworzyć zarejestrowaną aplikację z poziomu interfejsu wiersza polecenia platformy Azure, musisz zalogować się na koncie platformy Azure, na którym mają być wykonywane operacje. W tym celu możesz użyć az login polecenia i wprowadzić swoje poświadczenia w przeglądarce. Po zalogowaniu się do konta platformy Azure z poziomu interfejsu wiersza polecenia możemy wywołać az ad sp create-for-rbac polecenie , aby utworzyć zarejestrowaną aplikację i jednostkę usługi.

W poniższym przykładzie użyto interfejsu wiersza polecenia platformy Azure do utworzenia nowej zarejestrowanej aplikacji:

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

Polecenie az ad sp create-for-rbac zwróci listę właściwości jednostki usługi w formacie JSON. Skopiuj te wartości, aby można było ich użyć do utworzenia niezbędnych zmiennych środowiskowych w następnym kroku.

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

Ważne

Propagowanie przypisań ról platformy Azure może potrwać kilka minut.

Ustawianie zmiennych środowiskowych

Zestaw AZURE Identity SDK odczytuje wartości z trzech zmiennych środowiskowych w czasie wykonywania w celu uwierzytelnienia aplikacji. W poniższej tabeli opisano wartość ustawianą dla każdej zmiennej środowiskowej.

Zmienna środowiskowa Wartość
AZURE_CLIENT_ID appId wartość z wygenerowanego kodu JSON
AZURE_TENANT_ID tenant wartość z wygenerowanego kodu JSON
AZURE_CLIENT_SECRET password wartość z wygenerowanego kodu JSON

Ważne

Po ustawieniu zmiennych środowiskowych zamknij i otwórz ponownie okno konsoli. Jeśli używasz programu Visual Studio lub innego środowiska programistycznego, może być konieczne jego ponowne uruchomienie w celu zarejestrowania nowych zmiennych środowiskowych.

Po ustawieniu tych zmiennych powinno być możliwe użycie obiektu DefaultAzureCredential w kodzie w celu uwierzytelnienia wybranego klienta usługi.

Uwaga

Znajdź sfinalizowany kod dla tego przewodnika Szybki start w witrynie GitHub

Konfigurowanie

Tworzenie nowej aplikacji w języku C#

W oknie konsoli (takim jak cmd, PowerShell lub Bash) użyj dotnet new polecenia , aby utworzyć nową aplikację konsolową o nazwie ActiveDirectoryQuickstart. To polecenie tworzy prosty projekt języka C# "Hello World" z jednym plikiem źródłowym: Program.cs.

dotnet new console -o ActiveDirectoryAuthenticationQuickstart

Zmień katalog na nowo utworzony folder aplikacji i użyj dotnet build polecenia , aby skompilować aplikację.

cd ActiveDirectoryAuthenticationQuickstart
dotnet build

Instalowanie pakietów zestawu SDK

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

Korzystanie z pakietów zestawu SDK

Dodaj następujące using dyrektywy, aby Program.cs używać zestawów SDK usługi Azure Identity i Azure Storage.

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

Tworzenie wartości domyślnejAzureCredential

Na potrzeby tego przewodnika Szybki start użyjemy wartości DefaultAzureCredential . To poświadczenie jest odpowiednie dla środowisk produkcyjnych i deweloperskich. Ponieważ jest ona potrzebna dla każdej operacji, utwórzmy ją w Program.cs klasie . Dodaj następujący element na początku pliku .

private DefaultAzureCredential credential = new DefaultAzureCredential();

Wystawianie tokenu z jednostkami usługi

Teraz dodamy kod, który używa utworzonego poświadczenia do wystawiania tokenu dostępu VoIP. Ten kod zostanie wywołany później.

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

Wysyłanie wiadomości SMS z jednostkami usługi

W innym przykładzie używania jednostek usługi dodamy ten kod, który używa tego samego poświadczenia do wysyłania wiadomości 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;
}

Pisanie metody Main

Powinna Program.cs już istnieć metoda Main. Dodajmy kod, który wywoła wcześniej utworzony kod, aby zademonstrować użycie jednostek usługi:

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 Końcowy plik powinien wyglądać następująco:

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

Uruchamianie programu

Teraz powinno być możliwe uruchomienie aplikacji przy użyciu folderu dotnet run aplikacji. Dane wyjściowe powinny wyglądać podobnie do następujących:

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

Uwaga

Znajdź sfinalizowany kod dla tego przewodnika Szybki start w witrynie GitHub

Konfigurowanie

Tworzenie nowej aplikacji Node.js

Otwórz terminal lub okno polecenia utwórz nowy katalog dla aplikacji i przejdź do niego.

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

Uruchom polecenie npm init -y , aby utworzyć plik package.json z ustawieniami domyślnymi.

npm init -y

Instalowanie pakietów zestawu SDK

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

Tworzenie nowego pliku

Otwórz nowy plik za pomocą edytora tekstów i zapisz go jako index.js, umieszczamy nasz kod w tym pliku.

Korzystanie z pakietów zestawu SDK

Dodaj następujące require dyrektywy na początku, aby używać zestawów index.js SDK usługi Azure Identity i Azure Storage.

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

Tworzenie wartości domyślnejAzureCredential

Na potrzeby tego przewodnika Szybki start użyjemy wartości DefaultAzureCredential . To poświadczenie jest odpowiednie dla środowisk produkcyjnych i deweloperskich. Ponieważ jest to konieczne dla każdej operacji, utwórzmy ją w górnej części pliku index.js .

    const credential = new DefaultAzureCredential();

Tworzenie tożsamości i wystawianie tokenu za pomocą jednostek usługi

Następnie napiszemy funkcję, która tworzy nową tożsamość i wystawia token dla tej tożsamości. Użyjemy jej później do przetestowania konfiguracji jednostki usługi.

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

Wysyłanie wiadomości SMS z jednostkami usługi

Teraz napiszmy funkcję, która używa jednostek usługi do wysyłania wiadomości 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
    );
}

Pisanie funkcji main

Po utworzeniu naszych funkcji możemy teraz napisać funkcję główną w celu ich wywołania i zademonstrować użycie jednostek usługi:

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

Końcowy index.js plik powinien wyglądać następująco:

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

Uruchamianie programu

Po zakończeniu możesz uruchomić plik, wprowadzając go node index.js z katalogu projektu. Jeśli wszystko poszło dobrze, powinno zostać wyświetlone coś podobnego do poniższego.

    $ 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

Dodatkowe wymagania wstępne dotyczące języka Java

W przypadku języka Java potrzebne są również następujące elementy:

Uwaga

Znajdź sfinalizowany kod dla tego przewodnika Szybki start w witrynie GitHub

Konfigurowanie

Tworzenie nowej aplikacji Java

Otwórz terminal lub okno polecenia. Przejdź do katalogu, w którym chcesz utworzyć aplikację Java. Uruchom poniższe polecenie, aby wygenerować projekt Java z szablonu maven-archetype-quickstart.

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

Zauważysz, że zadanie "generate" utworzyło katalog o takiej samej nazwie jak artifactId. W tym katalogu katalog src/main/java zawiera kod źródłowy projektu, src/test/java directory zawiera źródło testowe, a pom.xml plik jest projektem Project Object Model lub POM.

Instalowanie pakietu

Otwórz plik pom.xml w edytorze tekstów. Dodaj następujący element zależności do grupy zależności.

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

Korzystanie z pakietów zestawu SDK

Dodaj następujące import dyrektywy do kodu, aby używać zestawów SDK usługi Azure Identity i Azure Communication.

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.*;

Tworzenie wartości domyślnejAzureCredential

Na potrzeby tego przewodnika Szybki start użyjemy wartości DefaultAzureCredential . To poświadczenie jest odpowiednie dla środowisk produkcyjnych i deweloperskich. Ponieważ jest ona potrzebna dla każdej operacji, utwórzmy ją w App.java klasie . Dodaj następujący kod do góry App.java klasy.

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

Wystawianie tokenu z jednostkami usługi

Teraz dodamy kod, który używa utworzonego poświadczenia do wystawiania tokenu dostępu VoIP. Ten kod zostanie wywołany później;

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

Wysyłanie wiadomości SMS z jednostkami usługi

W innym przykładzie używania jednostek usługi dodamy ten kod, który używa tego samego poświadczenia do wysyłania wiadomości 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);
     }

Pisanie metody Main

Powinna App.java już istnieć metoda Main. Dodajmy kod, który wywoła wcześniej utworzony kod, aby zademonstrować użycie jednostek usługi:

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

Twój finał App.java powinien wyglądać następująco:

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

Uruchamianie kodu

Przejdź do katalogu zawierającego plik pom.xml i skompiluj projekt przy użyciu następującego mvn polecenia.

mvn compile

Następnie skompiluj pakiet.

mvn package

Uruchom następujące mvn polecenie, aby wykonać aplikację.

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

Ostateczne dane wyjściowe powinny wyglądać podobnie do następujących:

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

Uwaga

Znajdź sfinalizowany kod dla tego przewodnika Szybki start w witrynie GitHub

Konfigurowanie

Tworzenie nowej aplikacji w języku Python

Otwórz terminal lub okno polecenia utwórz nowy katalog dla aplikacji i przejdź do niego.

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

Instalowanie pakietów zestawu SDK

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

Tworzenie nowego pliku

Otwórz i zapisz nowy plik w utworzonym folderze o nazwie authentication.py, umieścimy nasz kod w tym pliku.

Korzystanie z pakietów zestawu SDK

Dodaj następujące import instrukcje na początku pliku, aby użyć zainstalowanych zestawów SDK.

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

Tworzenie wartości domyślnejAzureCredential

Użyjemy wartości DefaultAzureCredential. To poświadczenie jest odpowiednie dla środowisk produkcyjnych i deweloperskich. W miarę używania go w tym przewodniku Szybki start utworzymy go w górnej części pliku.

     credential = DefaultAzureCredential()

Tworzenie tożsamości i wystawianie tokenu za pomocą jednostek usługi

Teraz dodamy kod, który używa utworzonego poświadczenia do wystawiania tokenu dostępu VoIP. Ten kod zostanie wywołany później w następujący sposób:

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

Wysyłanie wiadomości SMS z jednostkami usługi

W innym przykładzie używania jednostek usługi dodamy ten kod, który używa tego samego poświadczenia do wysyłania wiadomości 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
     )

Napisz nasz kod główny

Po utworzeniu naszych funkcji możemy teraz napisać kod główny, który będzie wywoływać funkcje, które zostały wcześniej napisane.

# 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}');

Końcowy authentication.py plik powinien wyglądać mniej więcej tak:

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}');

Uruchamianie programu

Po zakończeniu możesz uruchomić plik, wprowadzając go python authentication.py z katalogu projektu. Jeśli wszystko poszło dobrze, powinno zostać wyświetlone coś podobnego do poniższego.

    $ 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

Następne kroki