التشغيل السريع: المصادقة باستخدام معرف Microsoft Entra
ابدأ باستخدام Azure Communication Services باستخدام معرف Microsoft Entra. تدعم Communication Services Identity وSMS SDKs مصادقة Microsoft Entra.
هذه البداية السريعة يوضح لك كيفية تخويل الوصول إلى SDKs الهوية والرسائل القصيرة من بيئة Azure التي تدعم "Active Directory". كما يصف كيفية اختبار التعليمات البرمجية في بيئة تطوير عن طريق إنشاء أساس خدمة لعملك.
المتطلبات الأساسية
- حساب Azure مع اشتراك نشط. إنشاء حساب مجانًا
- مورد خدمات اتصالات Azure نشط، راجع إنشاء مورد خدمات الاتصال إذا لم يكن لديك واحد.
- لإرسال رسالة نصية قصيرة، ستحتاج إلى رقم الهاتف.
- إعداد كيان الخدمة لبيئة تطوير، راجع تخويل الوصول باستخدام كيان الخدمة
المتطلبات الأساسية الإضافية
- Azure CLI دليل التثبيت
الإعداد
عند استخدام خدمات مجالMicrosoft Azure Active Directory لـ Azure Resources الأخرى، يجب أن تستخدم الهويات المُدارة. لمعرفة كيفية تمكين الهويات المُدارة لـAzure Resources، راجع أحد هذه المقالات:
- مدخل Microsoft Azure
- Azure PowerShell
- Azure CLI
- قالب Azure Resource Manager
- عدد SDK لـAzure Resource Manager
- خدمات التطبيقات
توثيق تطبيق مسجل في بيئة التطوير
إذا كانت بيئة التطوير الخاصة بك لا تدعم تسجيل الدخول الأحادي أو تسجيل الدخول عبر مستعرض ويب، فيمكنك استخدام تطبيق مسجل للمصادقة من بيئة التطوير.
إنشاء تطبيق مسجل في Microsoft Entra
لإنشاء تطبيق مسجل من Azure CLI، يلزمك تسجيل الدخول إلى حساب Azure حيث تريد إجراء العمليات. للقيام بذلك، يمكنك استخدام الأمر az login
وإدخال بيانات الاعتماد الخاصة بك في المتصفح. بمجرد تسجيل الدخول إلى حساب Azure الخاص بك من CLI، يمكننا استدعاء az ad sp create-for-rbac
الأمر لإنشاء التطبيق المسجل ومدير الخدمة.
يستخدم المثال التالي Azure CLI لإنشاء تطبيق مسجل جديد:
az ad sp create-for-rbac --name <application-name> --role Contributor --scopes /subscriptions/<subscription-id>
سيقوم الأمر az ad sp create-for-rbac
بإرجاع قائمة بخصائص الخدمة الأساسية بتنسيق JSON. انسخ هذه القيم بحيث يمكنك استخدامها لإنشاء متغيرات البيئة الضرورية في الخطوة التالية.
{
"appId": "generated-app-ID",
"displayName": "service-principal-name",
"name": "http://service-principal-uri",
"password": "generated-password",
"tenant": "tenant-ID"
}
هام
قد تستغرق تعيينات الأدوار في Azure بضع دقائق.
تعيين متغيرات البيئة
تقرأ Azure Identity SDK القيم من ثلاثة متغيرات بيئة في وقت التشغيل لمصادقة التطبيق. يصف الجدول التالي القيمة المطلوب تعيينها لكل متغير بيئة.
متغير البيئة | القيمة |
---|---|
AZURE_CLIENT_ID |
قيمة appId من JSON الذي تم إنشاؤه |
AZURE_TENANT_ID |
قيمة tenant من JSON الذي تم إنشاؤه |
AZURE_CLIENT_SECRET |
قيمة password من JSON الذي تم إنشاؤه |
هام
بعد تعيين متغيرات البيئة، أغلق نافذة وحدة التحكم الخاصة بك وأعد فتحها. إذا كنت تستخدم Visual Studio أو بيئة تطوير أخرى، فقد تحتاج إلى إعادة تشغيله من أجل تسجيل متغيرات البيئة الجديدة.
بمجرد تعيين هذه المتغيرات، يجب أن تكون قادراً على استخدام كائن DefaultAzureCredential في التعليمات البرمجية الخاصة بك للمصادقة على عميل الخدمة الذي تختاره.
إشعار
ابحث عن التعليمات البرمجية النهائية لهذه البداية السريعة في GitHub.
الإعداد
إنشاء تطبيق C# جديد
في نافذة وحدة تحكم (مثل cmd أو PowerShell أو Bash)، استخدم الأمر dotnet new
لإنشاء تطبيق وحدة تحكم جديد بالاسم ActiveDirectoryQuickstart
. يقوم هذا الأمر بإنشاء مشروع "Hello World" بسيط بلغة C# باستخدام ملف مصدر واحد: Program.cs
.
dotnet new console -o ActiveDirectoryAuthenticationQuickstart
قم بتغيير الدليل الخاص بك إلى مجلد التطبيق الذي تم إنشاؤه حديثًا، واستخدم الأمر dotnet build
للتحويل البرمجي لتطبيقك.
cd ActiveDirectoryAuthenticationQuickstart
dotnet build
تثبيت حزم SDK
dotnet add package Azure.Communication.Identity
dotnet add package Azure.Communication.Sms
dotnet add package Azure.Identity
استخدام حِزم SDK
أضف التوجيهات التالية using
إلى Program.cs
لاستخدام Azure Identity وAzure Storage SDKs.
using Azure.Identity;
using Azure.Communication.Identity;
using Azure.Communication.Sms;
using Azure.Core;
using Azure;
إنشاء «DefaultAzureCredential»
سنستخدم DefaultAzureCredential لبدء التشغيل السريع هذا. بيانات الاعتماد هذه مناسبة لبيئات التشغيل والتطوير. كما هو مطلوب لكل عملية، دعونا نقوم بإنشائها داخل الفئة Program.cs
. إضافة ما يلي أعلى الملف.
private DefaultAzureCredential credential = new DefaultAzureCredential();
إصدار رمز مميز مع مديري الخدمة
الآن سنقوم بإضافة التعليمات البرمجية التي تستخدم بيانات الاعتماد التي تم إنشاؤها، لإصدار رمز الوصول VoIP. سنتصل بهذا الرمز لاحقا.
public AccessToken CreateIdentityAndGetTokenAsync(Uri resourceEndpoint)
{
var client = new CommunicationIdentityClient(resourceEndpoint, this.credential);
var result = client.CreateUserAndToken(scopes: new[] { CommunicationTokenScope.VoIP });
var (user, token) = response.Value;
return token;
}
إرسال رسالة نصية قصيرة باستخدام مبادئ الخدمات
كمثال آخر على استخدام كيانات الخدمة، سوف نقوم بإضافة هذا الرمز الذي يستخدم نفس بيانات الاعتماد لإرسال رسالة نصية قصيرة:
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.cs
بالفعل على أسلوب رئيسي، دعنا نضيف بعض التعليمات البرمجية التي ستستدعي التعليمة البرمجية التي تم إنشاؤها مسبقًا لتوضيح استخدام كيانات الخدمة:
static void Main(string[] args)
{
// You can find your endpoint and access key from your resource in the Azure portal
// e.g. "https://<RESOURCE_NAME>.communication.azure.com";
Uri endpoint = new("https://<RESOURCENAME>.communication.azure.com/");
// We need an instance of the program class to use within this method.
Program instance = new();
Console.WriteLine("Retrieving new Access Token, using Service Principals");
AccessToken response = instance.CreateIdentityAndGetTokenAsync(endpoint);
Console.WriteLine($"Retrieved Access Token: {response.Token}");
Console.WriteLine("Sending SMS using Service Principals");
// You will need a phone number from your resource to send an SMS.
SmsSendResult result = instance.SendSms(endpoint, "<Your Azure Communication Services Phone Number>", "<The Phone Number you'd like to send the SMS to.>", "Hello from using Service Principals");
Console.WriteLine($"Sms id: {result.MessageId}");
Console.WriteLine($"Send Result Successful: {result.Successful}");
}
يجب أن يبدو الملف النهائي Program.cs
كما يلي:
class Program
{
private DefaultAzureCredential credential = new DefaultAzureCredential();
static void Main(string[] args)
{
// You can find your endpoint and access key from your resource in the Azure portal
// e.g. "https://<RESOURCE_NAME>.communication.azure.com";
Uri endpoint = new("https://acstestingrifox.communication.azure.com/");
// We need an instance of the program class to use within this method.
Program instance = new();
Console.WriteLine("Retrieving new Access Token, using Service Principals");
AccessToken response = instance.CreateIdentityAndGetTokenAsync(endpoint);
Console.WriteLine($"Retrieved Access Token: {response.Token}");
Console.WriteLine("Sending SMS using Service Principals");
// You will need a phone number from your resource to send an SMS.
SmsSendResult result = instance.SendSms(endpoint, "<Your Azure Communication Services Phone Number>", "<The Phone Number you'd like to send the SMS to.>", "Hello from Service Principals");
Console.WriteLine($"Sms id: {result.MessageId}");
Console.WriteLine($"Send Result Successful: {result.Successful}");
}
public AccessToken CreateIdentityAndGetTokenAsync(Uri resourceEndpoint)
{
var client = new CommunicationIdentityClient(resourceEndpoint, this.credential);
var result = client.CreateUserAndToken(scopes: new[] { CommunicationTokenScope.VoIP });
var (user, token) = response.Value;
return token;
}
public SmsSendResult SendSms(Uri resourceEndpoint, string from, string to, string message)
{
SmsClient smsClient = new SmsClient(resourceEndpoint, this.credential);
SmsSendResult sendResult = smsClient.Send(
from: from,
to: to,
message: message,
new SmsSendOptions(enableDeliveryReport: true) // optional
);
return sendResult;
}
}
قم بتشغيل البرنامج.
يجب أن تكون الآن قادرا على تشغيل التطبيق الخاص بك، باستخدام dotnet run
من مجلد التطبيق الخاص بك. يجب أن يكون الإخراج مشابهًا لما يلي:
Retrieving new Access Token, using Service Principals
Retrieved Access Token: ey....
Sending SMS using Service Principals
Sms id: Outgoing_..._noam
Send Result Successful: True
إشعار
ابحث عن التعليمات البرمجية النهائية لهذه البداية السريعة في 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 Identity و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();
إنشاء هوية وإصدار رمز مميز مع أساسيات الخدمة
بعد ذلك، سنكتب دالة تنشئ هوية جديدة وتصدر رمزًا مميزًا لهذه الهوية، وسنستخدمها لاحقًا لاختبار الإعداد الرئيسي للخدمة.
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();
يجب أن يبدو ملف index.js
النهائي كما يلي:
const { DefaultAzureCredential } = require("@azure/identity");
const { CommunicationIdentityClient, CommunicationUserToken } = require("@azure/communication-identity");
const { SmsClient, SmsSendRequest } = require("@azure/communication-sms");
const credential = new DefaultAzureCredential();
async function createIdentityAndIssueToken(resourceEndpoint) {
const client = new CommunicationIdentityClient(resourceEndpoint, credential);
return await client.createUserAndToken(["chat"]);
}
async function sendSms(resourceEndpoint, fromNumber, toNumber, message) {
const smsClient = new SmsClient(resourceEndpoint, credential);
const sendRequest = {
from: fromNumber,
to: [toNumber],
message: message
};
return await smsClient.send(
sendRequest,
{} //Optional SendOptions
);
}
async function main() {
// You can find your endpoint and access key from your resource in the Azure portal
// e.g. "https://<RESOURCE_NAME>.communication.azure.com";
const endpoint = "https://<RESOURCE_NAME>.communication.azure.com/"
console.log("Retrieving new Access Token, using Service Principals");
const result = await createIdentityAndIssueToken(endpoint);
console.log(`Retrieved Access Token: ${result.token}`);
console.log("Sending SMS using Service Principals");
// You will need a phone number from your resource to send an SMS.
const smsResult = await sendSms(endpoint, "<FROM NUMBER>", "<TO NUMBER>", "Hello from Service Principals");
console.log(`SMS ID: ${smsResult[0].messageId}`);
console.log(`Send Result Successful: ${smsResult[0].successful}`);
}
main();
قم بتشغيل البرنامج.
بعد اكتمال كل شيء، يمكنك تشغيل الملف عن طريق إدخال node index.js
من دليل مشروعك. إذا سار كل شيء على ما يرام، يجب أن ترى شيئًا مماثلاً لما يلي.
$ node index.js
Retrieving new Access Token, using Service Principals
Retrieved Access Token: ey...Q
Sending SMS using Service Principals
SMS ID: Outgoing_2021040602194...._noam
Send Result Successful: true
متطلبات إضافية لـ Java
بالنسبة إلى Java، ستحتاج أيضا إلى:
- Java Development Kit (SDK) الإصدار 8 أو أحدث.
- Apache Maven.
إشعار
ابحث عن التعليمات البرمجية النهائية لهذه البداية السريعة في GitHub.
الإعداد
إنشاء تطبيق Java جديد
افتح نافذة المحطة الطرفية أو نافذة الأوامر. انتقل إلى الدليل الذي تريد إنشاء تطبيق Java فيه. تشغيل الأمر أدناه لإنشاء مشروع Java من قالب maven-archetype-quickstart.
mvn archetype:generate -DgroupId=com.communication.quickstart -DartifactId=communication-quickstart -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=false
ستلاحظ أن المهمة "إنشاء" أعدت دليلاً بنفس اسم artifactId
. ضمن هذا الدليل، يحتوي الدليل src/main/java على التعليمة البرمجية المصدر للمشروع، بينما يحتوي src/test/java directory
على مصدر الاختبار، أما الملف pom.xml
فهو نموذج كائن المشروع أو POM.
تثبيت الحزمة
افتح ملف pom.xml في محرر النص. أضف عنصر التبعية التالي إلى مجموعة التبعيات.
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-communication-identity</artifactId>
<version>[1.4.0,)</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-communication-sms</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.2.3</version>
</dependency>
استخدام حِزم SDK
أضف توجيهات import
التالية إلى التعليمات البرمجية لاستخدام Azure Identity وAzure Communication SDKs.
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();
}
إرسال رسالة نصية قصيرة باستخدام مبادئ الخدمات
كمثال آخر على استخدام كيانات الخدمة، سوف نقوم بإضافة هذا الرمز الذي يستخدم نفس بيانات الاعتماد لإرسال رسالة نصية قصيرة:
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);
}
كتابة الطريقة الرئيسية
يجب أن يحتوي App.java
بالفعل على أسلوب رئيسي، دعنا نضيف بعض التعليمات البرمجية التي ستستدعي التعليمة البرمجية التي تم إنشاؤها مسبقًا لتوضيح استخدام كيانات الخدمة:
public static void main(String[] args) {
App instance = new App();
// You can find your endpoint and access key from your resource in the Azure portal
// e.g. "https://<RESOURCE_NAME>.communication.azure.com";
String endpoint = "https://<RESOURCE_NAME>.communication.azure.com/";
System.out.println("Retrieving new Access Token, using Service Principals");
AccessToken token = instance.createIdentityAndGetTokenAsync(endpoint);
System.out.println("Retrieved Access Token: "+ token.getToken());
System.out.println("Sending SMS using Service Principals");
// You will need a phone number from your resource to send an SMS.
SmsSendResult result = instance.sendSms(endpoint, "<FROM NUMBER>", "<TO NUMBER>", "Hello from Service Principals");
System.out.println("Sms id: "+ result.getMessageId());
System.out.println("Send Result Successful: "+ result.isSuccessful());
}
يجب أن يبدو App.java
النهائي كما يلي:
package com.communication.quickstart;
import com.azure.communication.common.*;
import com.azure.communication.identity.*;
import com.azure.communication.identity.models.*;
import com.azure.communication.sms.*;
import com.azure.communication.sms.models.*;
import com.azure.core.credential.*;
import com.azure.identity.*;
import java.util.*;
public class App
{
private TokenCredential credential = new DefaultAzureCredentialBuilder().build();
public SmsSendResult sendSms(String endpoint, String from, String to, String message) {
SmsClient smsClient = new SmsClientBuilder()
.endpoint(endpoint)
.credential(this.credential)
.buildClient();
// Send the message and check the response for a message id
return smsClient.send(from, to, message);
}
public AccessToken createIdentityAndGetTokenAsync(String endpoint) {
CommunicationIdentityClient communicationIdentityClient = new CommunicationIdentityClientBuilder()
.endpoint(endpoint)
.credential(this.credential)
.buildClient();
CommunicationUserIdentifierAndToken result = communicationIdentityClient.createUserAndToken(new ArrayList<>(Arrays.asList(CommunicationTokenScope.CHAT)));
return result.getUserToken();
}
public static void main(String[] args) {
App instance = new App();
// You can find your endpoint and access key from your resource in the Azure portal
// e.g. "https://<RESOURCE_NAME>.communication.azure.com";
String endpoint = "https://<RESOURCE_NAME>.communication.azure.com/";
System.out.println("Retrieving new Access Token, using Service Principals");
AccessToken token = instance.createIdentityAndGetTokenAsync(endpoint);
System.out.println("Retrieved Access Token: "+ token.getToken());
System.out.println("Sending SMS using Service Principals");
// You will need a phone number from your resource to send an SMS.
SmsSendResult result = instance.sendSms(endpoint, "<FROM NUMBER>", "<TO NUMBER>", "Hello from Service Principals");
System.out.println("Sms id: "+ result.getMessageId());
System.out.println("Send Result Successful: "+ result.isSuccessful());
}
}
تشغيل التعليمات البرمجية
انتقل إلى الدليل الذي يحتوي على ملف pom.xml وترجمة المشروع باستخدام mvn
الأمر التالي.
mvn compile
ثم قم ببناء الحزمة.
mvn package
قم بتشغيل الأمر التالي mvn
لتنفيذ التطبيق.
mvn exec:java -Dexec.mainClass="com.communication.quickstart.App" -Dexec.cleanupDaemonThreads=false
يجب أن يبدو الناتج النهائي كما يلي:
Retrieving new Access Token, using Service Principals
Retrieved Access Token: ey..A
Sending SMS using using Service Principals
Sms id: Outgoing_202104...33f8ae1f_noam
Send Result Successful: true
إشعار
ابحث عن التعليمات البرمجية النهائية لهذه البداية السريعة في GitHub.
الإعداد
إنشاء تطبيق Python جديد
افتح المحطة الطرفية أو نافذة الأوامر لإنشاء دليل جديد لتطبيقك، ثم انتقل إليه.
mkdir active-directory-authentication-quickstart && cd active-directory-authentication-quickstart
تثبيت حزم SDK
pip install azure-identity
pip install azure-communication-identity
pip install azure-communication-sms
إنشاء ملف جديد
افتح ملفا جديدا واحفظه داخل المجلد الذي تم إنشاؤه باسم authentication.py
، وسنقوم بوضع التعليمات البرمجية الخاصة بنا داخل هذا الملف.
استخدام حِزم SDK
أضف العبارات التالية import
إلى أعلى الملف لاستخدام SDKs التي قمنا بتثبيتها.
from azure.identity import DefaultAzureCredential
from azure.communication.identity import CommunicationIdentityClient
from azure.communication.sms import SmsClient
إنشاء «DefaultAzureCredential»
سنستخدم DefaultAzureCredential. بيانات الاعتماد هذه مناسبة لبيئات التشغيل والتطوير. وأثناء استخدامها طوال هذا التشغيل السريع سنقوم بإنشائها في الجزء العلوي من الملف.
credential = DefaultAzureCredential()
إنشاء هوية وإصدار رمز مميز مع أساسيات الخدمة
الآن سنقوم بإضافة التعليمات البرمجية التي تستخدم بيانات الاعتماد التي تم إنشاؤها، لإصدار رمز الوصول VoIP. سنستدعي هذا الرمز لاحقًا:
def create_identity_and_get_token(resource_endpoint):
client = CommunicationIdentityClient(resource_endpoint, credential)
user, token_response = client.create_user_and_token(scopes=["voip"])
return token_response
إرسال رسالة نصية قصيرة باستخدام مبادئ الخدمات
كمثال آخر على استخدام كيانات الخدمة، سوف نقوم بإضافة هذا الرمز الذي يستخدم نفس بيانات الاعتماد لإرسال رسالة نصية قصيرة:
def send_sms(resource_endpoint, from_phone_number, to_phone_number, message_content):
sms_client = SmsClient(resource_endpoint, credential)
sms_client.send(
from_=from_phone_number,
to_=[to_phone_number],
message=message_content,
enable_delivery_report=True # optional property
)
كتابة تعليماتنا البرمجية الرئيسية
بإنشائنا للدوال يمكننا الآن كتابة التعليمات البرمجية الرئيسية التي ستستدعي الدوال التي كتبناها سابقًا.
# You can find your endpoint and access key from your resource in the Azure portal
# e.g. "https://<RESOURCE_NAME>.communication.azure.com";
endpoint = "https://<RESOURCE_NAME>.communication.azure.com/"
print("Retrieving new Access Token, using Service Principals");
result = create_identity_and_get_token(endpoint);
print(f'Retrieved Access Token: {result.token}');
print("Sending SMS using Service Principals");
# You will need a phone number from your resource to send an SMS.
sms_result = send_sms(endpoint, "<FROM_NUMBER>", "<TO_NUMBER>", "Hello from Service Principals");
print(f'SMS ID: {sms_result[0].message_id}');
print(f'Send Result Successful: {sms_result[0].successful}');
يجب أن يبدو الملف النهائي authentication.py
كما يلي:
from azure.identity import DefaultAzureCredential
from azure.communication.identity import CommunicationIdentityClient
from azure.communication.sms import SmsClient
credential = DefaultAzureCredential()
def create_identity_and_get_token(resource_endpoint):
client = CommunicationIdentityClient(resource_endpoint, credential)
user, token_response = client.create_user_and_token(scopes=["voip"])
return token_response
def send_sms(resource_endpoint, from_phone_number, to_phone_number, message_content):
sms_client = SmsClient(resource_endpoint, credential)
response = sms_client.send(
from_=from_phone_number,
to=[to_phone_number],
message=message_content,
enable_delivery_report=True # optional property
)
return response
# You can find your endpoint and access key from your resource in the Azure portal
# e.g. "https://<RESOURCE_NAME>.communication.azure.com";
endpoint = "https://<RESOURCE_NAME>.communication.azure.com/"
print("Retrieving new Access Token, using Service Principals");
result = create_identity_and_get_token(endpoint);
print(f'Retrieved Access Token: {result.token}');
print("Sending SMS using Service Principals");
# You will need a phone number from your resource to send an SMS.
sms_result = send_sms(endpoint, "<FROM_NUMBER>", "<TO_NUMBER>", "Hello from Service Principals");
print(f'SMS ID: {sms_result[0].message_id}');
print(f'Send Result Successful: {sms_result[0].successful}');
قم بتشغيل البرنامج.
بعد اكتمال كل شيء، يمكنك تشغيل الملف عن طريق إدخال python authentication.py
من دليل مشروعك. إذا سار كل شيء على ما يرام، يجب أن ترى شيئًا مماثلاً لما يلي.
$ python authentication.py
Retrieving new Access Token, using Service Principals
Retrieved Access Token: ey...Q
Sending SMS using using Service Principals
SMS ID: Outgoing_2021040602194...._noam
Send Result Successful: true