Hızlı Başlangıç: Microsoft Entra Id kullanarak kimlik doğrulaması

Microsoft Entra Id kullanarak Azure İletişim Hizmetleri'ne başlayın. İletişim Hizmetleri Kimliği ve SMS SDK'ları Microsoft Entra kimlik doğrulamasını destekler.

Bu hızlı başlangıçta, Active Directory'yi destekleyen bir Azure ortamından Kimlik ve SMS SDK'larına erişimi yetkilendirme işlemi gösterilmektedir. Ayrıca, çalışmanız için bir hizmet sorumlusu oluşturarak kodunuzu geliştirme ortamında nasıl test etmek istediğiniz de açıklanır.

Önkoşullar

Ek Önkoşullar

Kurulum

Diğer Azure Kaynakları için Active Directory kullanırken Yönetilen kimlikleri kullanıyor olmanız gerekir. Azure Kaynakları için yönetilen kimlikleri etkinleştirmeyi öğrenmek için şu makalelerden birine bakın:

Geliştirme ortamında kayıtlı bir uygulamanın kimliğini doğrulama

Geliştirme ortamınız bir web tarayıcısı aracılığıyla çoklu oturum açmayı veya oturum açmayı desteklemiyorsa, geliştirme ortamından kimlik doğrulaması yapmak için kayıtlı bir uygulama kullanabilirsiniz.

Microsoft Entra kayıtlı uygulaması oluşturma

Azure CLI'dan kayıtlı bir uygulama oluşturmak için işlemlerin gerçekleşmesini istediğiniz Azure hesabında oturum açmanız gerekir. Bunu yapmak için komutunu kullanabilir az login ve tarayıcıya kimlik bilgilerinizi girebilirsiniz. CLI'dan Azure hesabınızda oturum açtıktan sonra, kayıtlı uygulamayı ve hizmet sorumlusunu az ad sp create-for-rbac oluşturmak için komutunu çağırabiliriz.

Aşağıdaki örnek, yeni bir kayıtlı uygulama oluşturmak için Azure CLI'yi kullanır:

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

Komut, az ad sp create-for-rbac JSON biçiminde hizmet sorumlusu özelliklerinin listesini döndürür. Bu değerleri kopyalayarak sonraki adımda gerekli ortam değişkenlerini oluşturabilmenizi sağlayın.

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

Önemli

Azure rol atamalarının yayılması birkaç dakika sürebilir.

Ortam değişkenlerini belirleme

Azure Kimlik SDK'sı, uygulamanın kimliğini doğrulamak için çalışma zamanında üç ortam değişkeninden değerleri okur. Aşağıdaki tabloda her ortam değişkeni için ayarlanacağı değer açıklanmaktadır.

Ortam değişkeni Değer
AZURE_CLIENT_ID appId oluşturulan JSON'dan değer
AZURE_TENANT_ID tenant oluşturulan JSON'dan değer
AZURE_CLIENT_SECRET password oluşturulan JSON'dan değer

Önemli

Ortam değişkenlerini ayarladıktan sonra konsol pencerenizi kapatıp yeniden açın. Visual Studio veya başka bir geliştirme ortamı kullanıyorsanız, yeni ortam değişkenlerini kaydetmek için yeniden başlatmanız gerekebilir.

Bu değişkenler ayarlandıktan sonra, seçtiğiniz hizmet istemcisinde kimlik doğrulaması yapmak için kodunuzda DefaultAzureCredential nesnesini kullanabilmeniz gerekir.

Uyarı

GitHub'da bu hızlı başlangıcın son halini alan kodu bulun

Genel Bakış

Bu hızlı başlangıçta, Azure İletişim Hizmetleri ile kimlik doğrulaması yapmak için Azure Hizmet Sorumluları aracılığıyla yönetilen kimliklerin nasıl kullanılacağı gösterilmektedir. IP üzerinden ses (VoIP) çağrıları için erişim belirteci verme ve SMS mesajları gönderme örnekleri sağlar.

Kurulum

Yeni bir C# uygulaması oluşturun.

Amaç, hızlı başlangıç kodunu çalıştırmak için C# dilinde yeni bir konsol uygulaması oluşturmaktır. Bir terminal penceresi açın (örneğin, Komut İstemi, PowerShell veya Bash) ve aşağıdaki komutu yürüterek adlı ActiveDirectoryAuthenticationQuickstartyeni bir konsol uygulaması oluşturun:

dotnet new console -o ActiveDirectoryAuthenticationQuickstart

Bu komut, tek bir kaynak dosyası da dahil olmak üzere basit bir "Hello World" C# projesi oluşturur: Program.cs.

Uygulamayı İnşa Et

Yeni oluşturulan uygulama klasörüne gidin ve komutunu kullanarak uygulamanızı derleyin dotnet build :

cd ActiveDirectoryAuthenticationQuickstart
dotnet build

Gerekli SDK Paketlerini Yükleme

Azure İletişim Hizmetleri ve Azure Identity ile etkileşime geçmek için projenize aşağıdaki NuGet paketlerini ekleyin:

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

Program.cs dosyasını güncelleştirme

Yüklü Azure SDK paketlerini kullanmak için dosyanızın using en üstüne aşağıdaki Program.cs yönergeleri ekleyin:

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

DefaultAzureCredential ile kimlik doğrulaması

Bu hızlı başlangıçta hem geliştirme hem de üretim ortamları için uygun olan DefaultAzureCredential'ı kullanacağız. Bu kimlik bilgisinin bir örneğini sınıf düzeyinde Program.cs içinde bildirin.

private DefaultAzureCredential credential = new DefaultAzureCredential();

Hizmet sorumlularıyla belirteç verme

Aşağıdaki yöntemi dosyanıza Program.cs ekleyin. Bu yöntem, VoIP Erişim Belirteci vermek için Azure İletişim Hizmetleri SDK'sını kullanır:

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

Hizmet sorumlularıyla SMS gönderme

SMS göndermeyi göstermek için dosyanıza Program.cs aşağıdaki yöntemi ekleyin. Bu yöntem, SMS iletisi göndermek için Azure İletişim Hizmetleri SDK'sını kullanır:

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

Dosyanızın Main dosyasının Program.cs yönteminde, oluşturduğunuz belirteç verme ve SMS gönderme yöntemlerini çağırmak için kod ekleyin. Yönteminiz Main şuna benzer görünmelidir:

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

Son Program.cs dosyanız şu şekilde görünmelidir:

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

Programı çalıştırma

Uygulamanızı çalıştırmanın ve bir erişim belirteci alıp SMS gönderdiğini doğrulamanın zamanı geldi. Bir terminal açın, uygulama dizininize gidin ve şunu çalıştırın:

     dotnet run

Konsol çıkışı aşağıdaki gibi görünmelidir:

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

Uyarı

GitHub'da bu hızlı başlangıcın son halini alan kodu bulun

Kurulum

Yeni bir Node.js uygulaması oluşturma

Terminalinizi veya komut pencerenizi açın, uygulamanız için yeni bir dizin oluşturun ve bu dizine gidin.

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

npm init -y komutunu çalıştırarak varsayılan ayarlarla bir package.json dosyası oluşturun.

npm init -y

SDK paketlerini yükleme

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

Yeni dosya oluşturma

Metin düzenleyicisiyle yeni bir dosya açın ve olarak index.jskaydedin. Kodumuzu bu dosyanın içine yerleştireceğiz.

SDK paketlerini kullanma

Azure Kimliği ve Azure Depolama SDK'larını require kullanmak için üst kısmına aşağıdaki index.js yönergeleri ekleyin.

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

DefaultAzureCredential Oluşturma

Bu hızlı başlangıç için DefaultAzureCredential kullanacağız. Bu kimlik bilgisi üretim ve geliştirme ortamları için uygundur. Her işlem için gerektiğinden, bunu dosyamızın index.js en üstünde oluşturalım.

    const credential = new DefaultAzureCredential();

Kimlik oluşturma ve hizmet sorumlularıyla belirteç verme

Ardından, yeni bir kimlik oluşturan ve bu kimlik için belirteç veren bir işlev yazacağız. Bunu daha sonra hizmet sorumlusu kurulumumuzu test etmek için kullanacağız.

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

Hizmet sorumlularıyla SMS gönderme

Şimdi sms göndermek için hizmet sorumlularını kullanan bir işlev yazalım:

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 işlevi yaz

İşlevlerimiz oluşturulduktan sonra artık bunları çağırmak ve Hizmet Sorumlularının kullanımını göstermek için bir ana işlev yazabiliriz:

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

Son index.js dosya aşağıdaki gibi görünmelidir:

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

Programı çalıştırma

Her şey tamamlandıktan sonra, projenizin dizininden girerek node index.js dosyayı çalıştırabilirsiniz. Her şey yolunda gittiyse aşağıdakine benzer bir şey görmeniz gerekir.

    $ 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 için ek önkoşullar

Java için şunları da yapmanız gerekir:

Uyarı

GitHub'da bu hızlı başlangıcın son halini alan kodu bulun

Kurulum

Yeni bir Java uygulaması oluşturun

Terminalinizi veya komut penceresini açın. Java uygulamanızı oluşturmak istediğiniz dizine gidin. Maven-archetype-quickstart şablonundan Java projesi oluşturmak için aşağıdaki komutu çalıştırın.

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

'Oluştur' görevinin, artifactId ile aynı ada sahip bir dizin oluşturduğunu göreceksiniz. Bu dizin altında, src/main/java dizini proje kaynak kodunu içerir, src/test/java directory test kaynağını içerir ve pom.xml dosya projenin Proje Nesne Modeli veya POM'dir.

Paketi yükle

pom.xml dosyasını metin düzenleyicinizde açın. Aşağıdaki bağımlılık öğesini bağımlılık grubuna ekleyin.

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

Azure Kimliği ve Azure İletişim SDK'larını kullanmak için kodunuza aşağıdaki import yönergeleri ekleyin.

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 Oluşturma

Bu hızlı başlangıç için DefaultAzureCredential kullanacağız. Bu kimlik bilgisi üretim ve geliştirme ortamları için uygundur. Her işlem için gerektiğinden, bunu App.java sınıfı içinde oluşturalım. Sınıfın başına App.java aşağıdakileri ekleyin.

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

Hizmet sorumlularıyla belirteç verme

Şimdi bir VoIP Erişim Belirteci vermek için oluşturulan kimlik bilgilerini kullanan kodu ekleyeceğiz. Bu kodu daha sonra çağıracağız;

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

Hizmet sorumlularıyla SMS gönderme

Hizmet sorumlularını kullanmanın başka bir örneği olarak, SMS göndermek için aynı kimlik bilgilerini kullanan bu kodu ekleyeceğiz:

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

Zaten bir Main yönteminiz App.java olmalıdır, şimdi hizmet sorumlularının kullanımını göstermek için önceden oluşturulmuş kodumuzu çağıracak bazı kodlar ekleyelim:

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

Finaliniz App.java şu şekilde görünmelidir:

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

Kodu çalıştır

pom.xml dosyasını içeren dizine gidin ve aşağıdaki mvn komutu kullanarak projeyi derleyin.

mvn compile

Ardından paketi oluşturun.

mvn package

Uygulamayı yürütmek için aşağıdaki mvn komutu çalıştırın.

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

Son çıkış aşağıdakine benzemelidir:

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

Uyarı

GitHub'da bu hızlı başlangıcın son halini alan kodu bulun

Kurulum

Yeni bir Python uygulaması oluşturun

Uygulama için çalışma dizininizi ayarlayalım. Bunun için terminalinizi veya komut pencerenizi açın, yeni bir dizin oluşturun ve bu dizine gidin:

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

SDK paketlerini yükleme

Ardından gerekli Azure SDK paketlerini yüklemeliyiz. Şu komutları çalıştırın:

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

Yeni dosya oluşturma

Şimdi kodunuzu tutmak için bir Python dosyasına ihtiyacımız var. Dizininizde adlı authentication.py yeni bir dosya açın ve kaydedin.

SDK paketlerini kullanma

Bir sonraki hedefimiz, kimlik ve SMS ile çalışmak için gerekli Azure SDK modüllerini içeri aktarmaktır. Dosyanızın en üstüne aşağıdaki deyimleri ekleyin:

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

DefaultAzureCredential Oluşturma

Hem üretim hem de geliştirme ortamları için bir kimlik bilgisi oluşturmamız gerekir.

Bu satırı DefaultAzureCredential ile önceden eklenen satırlara yerleştirin:

     credential = DefaultAzureCredential()

Kimlik oluşturma ve hizmet sorumlularıyla belirteç verme

Kimlik oluşturun ve İnternet Protokolü Üzerinden Ses (VoIP) erişim belirteci isteyin:

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

Hizmet sorumlularıyla SMS gönderme

Alternatif olarak, aşağıdaki örnekte gösterildiği gibi kısa mesaj hizmeti (SMS) göndermek için kimlik bilgilerinizi kullanabilirsiniz:

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
     )

Ana kodumuzu yazın

Artık kimlik oluşturmak, erişim belirteci almak ve SMS göndermek için işlevleri yürütmek için gerekli tüm kod bloklarına sahibiz.

İşlevlerinizi çağıran ana kodu ekleyin:

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

Yaptığınız tüm değişikliklerden sonra authentication.py şöyle görünüyor:

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

Programı çalıştırma

İşlevselliği doğrulamak için Python betiğinizi yürütmenin zamanı geldi. Dosyasını projenizin dizininden komutunu kullanarak çalıştırın:

python authentication.py

Başarılı olursa, görmekte olduğunuz çıktı buna benzeyecektir:

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

Sonraki Adımlar