Delen via


Quickstart: Verifiëren met behulp van Microsoft Entra-id

Ga aan de slag met Azure Communication Services met behulp van Microsoft Entra ID. De Communication Services Identity- en SMS-SDK's ondersteunen Microsoft Entra-verificatie.

In deze quickstart ziet u hoe u toegang tot de IDENTITEITS- en SMS-SDK's kunt autoriseren vanuit een Azure-omgeving die Active Directory ondersteunt. Ook wordt beschreven hoe u uw code in een ontwikkelomgeving test door een service-principal voor uw werk te maken.

Vereiste voorwaarden

Aanvullende vereisten

  • Azure CLI. Installatiehandleiding

Instellen

Wanneer u Active Directory gebruikt voor andere Azure-resources, moet u beheerde identiteiten gebruiken. Zie een van de volgende artikelen voor meer informatie over het inschakelen van beheerde identiteiten voor Azure-resources:

Een geregistreerde toepassing verifiëren in de ontwikkelomgeving

Als uw ontwikkelomgeving geen ondersteuning biedt voor eenmalige aanmelding of aanmelding via een webbrowser, kunt u een geregistreerde toepassing gebruiken om te verifiëren vanuit de ontwikkelomgeving.

Een geregistreerde Microsoft Entra-toepassing maken

Als u een geregistreerde toepassing wilt maken vanuit de Azure CLI, moet u zijn aangemeld bij het Azure-account waar u de bewerkingen wilt uitvoeren. Hiervoor kunt u de az login opdracht gebruiken en uw referenties invoeren in de browser. Zodra u bent aangemeld bij uw Azure-account via de CLI, kunnen we het az ad sp create-for-rbac commando uitvoeren om de geregistreerde toepassing en service-principal te maken.

In het volgende voorbeeld wordt de Azure CLI gebruikt om een nieuwe geregistreerde toepassing te maken:

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

De az ad sp create-for-rbac opdracht retourneert een lijst met eigenschappen van de service principal in JSON-indeling. Kopieer deze waarden zodat u ze kunt gebruiken om de benodigde omgevingsvariabelen te maken in de volgende stap.

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

Belangrijk

Het kan enkele minuten duren voordat Azure-roltoewijzingen zijn gepropageerd.

Omgevingsvariabelen instellen

De Azure Identity SDK leest waarden uit drie omgevingsvariabelen tijdens runtime om de toepassing te verifiëren. In de volgende tabel wordt de waarde beschreven die moet worden ingesteld voor elke omgevingsvariabele.

Omgevingsvariabele Waarde
AZURE_CLIENT_ID appId waarde van de gegenereerde JSON
AZURE_TENANT_ID tenant waarde van de gegenereerde JSON
AZURE_CLIENT_SECRET password waarde van de gegenereerde JSON

Belangrijk

Nadat u de omgevingsvariabelen hebt ingesteld, sluit en opent u het consolevenster opnieuw. Als u Visual Studio of een andere ontwikkelomgeving gebruikt, moet u deze mogelijk opnieuw opstarten om de nieuwe omgevingsvariabelen te kunnen registreren.

Zodra deze variabelen zijn ingesteld, moet u het DefaultAzureCredential-object in uw code kunnen gebruiken om te verifiëren bij de serviceclient van uw keuze.

Opmerking

Vind de voltooide code voor deze quickstart op GitHub

Overzicht

In deze quickstart ziet u hoe u beheerde identiteiten gebruikt via Azure Service Principals voor verificatie met Azure Communication Services. Het bevat voorbeelden voor het uitgeven van een toegangstoken voor VoIP-oproepen (Voice over IP) en het verzenden van SMS-berichten.

Installeren

Maak een nieuwe C#-applicatie

Het doel is om een nieuwe consoletoepassing te maken in C# om de quickstart-code uit te voeren. Open een terminalvenster (bijvoorbeeld opdrachtprompt, PowerShell of Bash) en voer de volgende opdracht uit om een nieuwe console-app met de naam ActiveDirectoryAuthenticationQuickstartte maken:

dotnet new console -o ActiveDirectoryAuthenticationQuickstart

Met deze opdracht wordt een eenvoudig "Hallo wereld" C#-project gegenereerd, inclusief één bronbestand: Program.cs.

De toepassing bouwen

Navigeer naar de zojuist gemaakte app-map en compileer uw toepassing met behulp van de dotnet build opdracht:

cd ActiveDirectoryAuthenticationQuickstart
dotnet build

De vereiste SDK-pakketten installeren

Als u wilt communiceren met Azure Communication Services en Azure Identity, voegt u de volgende NuGet-pakketten toe aan uw project:

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

Het Program.cs-bestand bijwerken

Als u de geïnstalleerde Azure SDK-pakketten wilt gebruiken, moet u de volgende using instructies boven aan het Program.cs bestand opnemen:

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

Verifiëren met DefaultAzureCredential

Voor deze quickstart gebruiken we de DefaultAzureCredential, die geschikt is voor zowel ontwikkel- als productieomgevingen. Declareer een exemplaar van deze referentie op klasseniveau in Program.cs:

private DefaultAzureCredential credential = new DefaultAzureCredential();

Een token uitgeven met service principals

Voeg de volgende methode toe aan uw Program.cs bestand. Deze methode maakt gebruik van de Azure Communication Services SDK om een VoIP-toegangstoken uit te geven:

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

Een sms met service-principals verzenden

Als u wilt laten zien hoe u een sms verzendt, voegt u de volgende methode toe aan uw Program.cs bestand. Deze methode maakt gebruik van de Azure Communication Services SDK om een SMS-bericht te verzenden:

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

De Main-methode schrijven

Voeg in de Main methode van uw Program.cs bestand code toe om de methoden aan te roepen die u hebt gemaakt voor het uitgeven van een token en het verzenden van een sms. Uw Main methode moet er ongeveer als volgt uitzien:

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

Het uiteindelijke Program.cs bestand moet er als volgt uitzien:

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

Het programma uitvoeren

Het is tijd om uw toepassing uit te voeren en te controleren of er een toegangstoken wordt opgehaald en een sms wordt verzonden. Open een terminal, navigeer naar uw toepassingsmap en voer het volgende uit:

     dotnet run

De console-uitvoer moet er als volgt uitzien:

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

Opmerking

Vind de voltooide code voor deze quickstart op GitHub

Installeren

Een nieuwe Node.js-toepassing maken

Open uw terminal of opdrachtvenster, maak een nieuwe map voor uw app en navigeer daar naartoe.

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

Voer npm init -y uit om een package.json-bestand te maken met de standaardinstellingen.

npm init -y

De SDK-pakketten installeren

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

Een nieuw bestand maken

Open een nieuw bestand met een teksteditor en sla het op als index.js, we plaatsen onze code in dit bestand.

De SDK-pakketten gebruiken

Voeg de volgende require instructies toe aan de bovenkant van index.js om de Azure Identity en Azure Storage SDK's te gebruiken.

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

Een DefaultAzureCredential maken

We gebruiken de DefaultAzureCredential voor deze snelle start. Deze referentie is geschikt voor productie- en ontwikkelomgevingen. Omdat het nodig is voor elke bewerking, maken we deze boven aan het index.js bestand.

    const credential = new DefaultAzureCredential();

Een identiteit creëren en een token verstrekken met serviceprincipals

Vervolgens schrijven we een functie die een nieuwe identiteit maakt en een token voor deze identiteit uitgeeft. We gebruiken deze later om de installatie van de service-principal te testen.

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

Een sms met service-principals verzenden

Laten we nu een functie schrijven die gebruikmaakt van service-principals om een sms te verzenden:

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

De hoofdfunctie schrijven

Nu onze functies zijn gemaakt, kunnen we nu een hoofdfunctie schrijven om deze aan te roepen en het gebruik van service-principals te demonstreren:

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

Het uiteindelijke index.js bestand moet er als volgt uitzien:

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

Het programma uitvoeren

Als alles is voltooid, kunt u het bestand uitvoeren door het bestand in te voeren node index.js vanuit de map van uw project. Als alles goed ging, ziet u iets vergelijkbaars met het volgende.

    $ 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

Aanvullende vereisten voor Java

Voor Java hebt u ook het volgende nodig:

Opmerking

Vind de voltooide code voor deze quickstart op GitHub

Installeren

Een nieuwe Java-toepassing maken

Open je terminal of opdrachtvenster. Navigeer naar de map waarin u uw Java-toepassing wilt maken. Voer de onderstaande opdracht uit om het Java-project te genereren op basis van de maven-archetype-snelstart-sjabloon.

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

U ziet dat de taak ' genereren ' een map heeft gemaakt met dezelfde naam als de artifactId. In deze map bevat de map src/main/Java de broncode van het project, de src/test/java directory bevat de testbron en het bestand pom.xml het projectobjectmodel van het project of POM.

Installeer het pakket

Open het bestand pom.xml in uw teksteditor. Voeg het volgende afhankelijkheidselement toe aan de groep met afhankelijkheden.

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

De SDK-pakketten gebruiken

Voeg de volgende import instructies toe aan uw code om de Azure Identity- en Azure Communication SDK's te gebruiken.

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

Een DefaultAzureCredential maken

We gebruiken de DefaultAzureCredential voor deze snelle start. Deze referentie is geschikt voor productie- en ontwikkelomgevingen. Omdat deze nodig is voor elke bewerking, gaan we deze in de App.java klasse maken. Voeg het volgende toe aan het begin van de App.java klasse.

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

Een token uitgeven met service principals

Nu gaan we code toevoegen die gebruikmaakt van de gemaakte referentie om een VoIP-toegangstoken uit te geven. Deze code wordt later aangeroepen.

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

Een sms met service-principals verzenden

Als een ander voorbeeld van het gebruik van service-principals voegen we deze code toe die dezelfde referentie gebruikt om een sms te verzenden:

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

De Main-methode schrijven

Je App.java heeft waarschijnlijk al een Main-methode, terwijl we wat code toevoegen die onze eerder gemaakte code aanroept om te demonstreren hoe je serviceprincipalen gebruikt.

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

Uw laatste App.java moet er als volgt uitzien:

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

De code uitvoeren

Navigeer naar de map die het bestand pom.xml bevat en compileer het project met behulp van de volgende mvn-opdracht.

mvn compile

Bouw vervolgens het pakket.

mvn package

Voer de volgende mvn-opdracht uit om de app uit te voeren.

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

De uiteindelijke uitvoer moet er ongeveer als volgt uitzien:

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

Opmerking

Vind de voltooide code voor deze quickstart op GitHub

Installeren

Maak een nieuwe Python-applicatie

Laten we uw werkmap instellen voor de toepassing. Open hiervoor het terminal- of opdrachtvenster, maak een nieuwe map en navigeer ernaartoe:

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

De SDK-pakketten installeren

Vervolgens moeten we de vereiste Azure SDK-pakketten installeren. Voer deze opdrachten uit:

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

Een nieuw bestand maken

Nu hebben we een Python-bestand nodig om uw code op te slaan. Open en sla een nieuw bestand op dat authentication.py genoemd wordt binnen je map.

De SDK-pakketten gebruiken

Het volgende doel is om de benodigde Azure SDK-modules te importeren om te werken met identiteit en sms. Voeg de volgende verklaringen toe bovenaan het bestand:

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

Een DefaultAzureCredential maken

We moeten inloggegevens initialiseren voor zowel productie- als ontwikkelingsomgevingen.

Plaats deze regel met DefaultAzureCredential nadat u eerder regels hebt ingevoegd:

     credential = DefaultAzureCredential()

Een identiteit creëren en een token verstrekken met serviceprincipals

Maak een identiteit en vraag een VoIP-toegangstoken (Voice over Internet Protocol):

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

Een sms met service-principals verzenden

U kunt ook uw referenties gebruiken om een sms (Short Message Service) te verzenden, zoals wordt weergegeven in het onderstaande voorbeeld:

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
     )

Onze hoofdcode schrijven

Nu hebben we alle benodigde codeblokken om de functies uit te voeren om een identiteit te maken, een toegangstoken te verkrijgen en een sms te verzenden.

Neem de hoofdcode op die uw functies aanroept:

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

Dit is hoe het authentication.py eruitziet na alle wijzigingen die u hebt aangebracht:

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

Het programma uitvoeren

Het is tijd om uw Python-script uit te voeren om de functionaliteit te verifiëren. Voer het bestand uit vanuit de map van uw project met de opdracht:

python authentication.py

Als dit lukt, ziet u uitvoer die er ongeveer als volgt uit ziet:

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

Volgende stappen