快速入門:建立和管理存取令牌

存取令牌可讓 Azure 通訊服務 SDK 直接向 Azure 通訊服務 驗證作為特定身分識別。 如果您希望使用者加入應用程式內的通話或聊天對話,您必須建立存取令牌。

在本快速入門中,您將瞭解如何使用 Azure 通訊服務 SDK 來建立身分識別及管理您的存取令牌。 針對生產使用案例,建議您在伺服器端服務產生存取令牌。

必要條件

設定

新增擴充功能

使用 az extension 命令新增 Azure CLI 的 Azure 通訊服務 擴充功能。

az extension add --name communication

登入 Azure CLI

您必須登入 Azure CLI。 您可以從終端機登入 az login ,並提供您的認證。

(選擇性)使用 Azure CLI 身分識別作業而不傳入 連接字串

您可以將環境變數設定AZURE_COMMUNICATION_CONNECTION_STRING為使用 Azure CLI 身分識別作業,而不需要使用 --connection_string 傳入 連接字串。 若要設定環境變數,請開啟控制台視窗,然後從下列索引標籤中選取您的作業系統。 將 <yourConnectionString> 用實際的連接字串取代。

開啟主控台視窗,然後輸入下列命令:

setx AZURE_COMMUNICATION_CONNECTION_STRING "<yourConnectionString>"

新增環境變數之後,您可能需要重新啟動任何需要讀取環境變數的執行中程式,包括主控台視窗。 例如,如果您使用 Visual Studio 作為編輯器,請在執行範例前重新啟動 Visual Studio。

將您的存取令牌儲存在環境變數中

若要設定環境變數,請開啟控制台視窗,然後從下列索引標籤中選取您的作業系統。 將取代 <yourAccessToken> 為您的實際存取令牌。

開啟主控台視窗,然後輸入下列命令:

setx AZURE_COMMUNICATION_ACCESS_TOKEN "<yourAccessToken>"

新增環境變數之後,您可能需要重新啟動任何需要讀取環境變數的執行中程式,包括主控台視窗。 例如,如果您使用 Visual Studio 作為編輯器,請在執行範例前重新啟動 Visual Studio。

Operations

建立身分識別

若要建立存取令牌,您需要身分識別。 Azure 通訊服務 針對此目的維護輕量型身分識別目錄。 user create使用 命令在目錄中建立具有唯Id一 的專案。 稍後需要身分識別,才能發行存取令牌。

az communication identity user create --connection-string "<yourConnectionString>"
  • <yourConnectionString> 取代為實際的連接字串。

在相同的要求中建立身分識別併發出存取令牌

執行下列命令來建立通訊服務身分識別,並同時為其發出存取令牌。 參數 scopes 會定義一組存取令牌許可權和角色。 如需詳細資訊,請參閱驗證至 Azure 通訊服務支援的動作清單。

az communication identity token issue --scope chat --connection-string "<yourConnectionString>"

在程式代碼中進行此取代:

  • <yourConnectionString> 取代為實際的連接字串。

問題存取令牌

執行下列命令,為您的通訊服務身分識別發出存取令牌。 參數 scopes 會定義一組存取令牌許可權和角色。 如需詳細資訊,請參閱驗證至 Azure 通訊服務支援的動作清單。

az communication identity token issue --scope chat --user "<userId>" --connection-string "<yourConnectionString>"

在程式代碼中進行此取代:

  • <yourConnectionString> 取代為實際的連接字串。
  • 將取代 <userId> 為您的userId。

存取令牌是需要重新發出之短期認證。 這樣做可能會導致應用程式用戶體驗中斷。 expires_on回應屬性表示存取令牌的存留期。

使用多個範圍發出存取令牌

執行下列命令,以發出具有通訊服務身分識別多個範圍的存取令牌。 參數 scopes 會定義一組存取令牌許可權和角色。 如需詳細資訊,請參閱身分識別模型中支持的動作清單。

az communication identity token issue --scope chat voip --user "<userId>" --connection-string "<yourConnectionString>"

在程式代碼中進行此取代:

  • <yourConnectionString> 取代為實際的連接字串。
  • 將取代 <userId> 為您的userId。

存取令牌是需要重新發出之短期認證。 這樣做可能會導致應用程式用戶體驗中斷。 expires_on回應屬性表示存取令牌的存留期。

交換 Teams 使用者的 Microsoft Entra 存取令牌,以取得通訊身分識別存取令牌

token get-for-teams-user使用 命令,為可與 Azure 通訊服務 SDK 搭配使用的 Teams 用戶發出存取令牌。

az communication identity token get-for-teams-user --aad-token "<yourAadToken>" --client "<yourAadApplication>" --aad-user "<yourAadUser>" --connection-string "<yourConnectionString>"

在程式代碼中進行此取代:

  • <yourConnectionString> 取代為實際的連接字串。
  • 以您的 Microsoft Entra userId 取代 <yourAadUser>
  • 將取代 <yourAadApplication> 為您的 Microsoft Entra 應用程式識別碼。
  • 將取代 <yourAadToken> 為您的 Microsoft Entra 存取令牌。

撤銷存取令牌

您偶爾可能需要明確撤銷存取令牌。 例如,當應用程式使用者變更其用來向服務進行驗證的密碼時,您會這麼做。 命令 token revoke 會使發出給身分識別的所有作用中存取令牌失效。

az communication identity token revoke --user "<userId>" --connection-string "<yourConnectionString>"

在程式代碼中進行此取代:

  • <yourConnectionString> 取代為實際的連接字串。
  • 將取代 <userId> 為您的userId。

刪除身分識別

當您刪除身分識別時,您會撤銷所有作用中的存取令牌,並防止進一步發行身分識別的存取令牌。 這樣做也會移除與身分識別相關聯的所有保存內容。

az communication identity user delete --user "<userId>" --connection-string "<yourConnectionString>"

在程式代碼中進行此取代:

  • <yourConnectionString> 取代為實際的連接字串。
  • 將取代 <userId> 為您的userId。

必要條件

最終程式碼

在 GitHub尋找本快速入門的完成程式代碼。

設定您的環境

建立新的 C# 應用程式

在命令提示字元視窗中,例如 cmd、PowerShell 或 Bash,執行 dotnet new 命令以建立名稱為 AccessTokensQuickstart的新控制台應用程式。 此命令會建立具有單一原始程式檔的簡單 「Hello World」 C# 專案, Program.cs

dotnet new console -o AccessTokensQuickstart

將目錄變更為新建立的應用程式資料夾,並使用 dotnet build 命令編譯您的應用程式。

cd AccessTokensQuickstart
dotnet build

應該會顯示簡單的 「Hello World」 輸出。 如果是,您的設定正常運作,而且您可以開始撰寫 Azure 通訊服務 特定程序代碼。

Install the package

當您仍在應用程式目錄中時,請使用 dotnet add package 命令安裝適用於 .NET 套件的 Azure 通訊服務 身分識別連結庫。

dotnet add package Azure.Communication.Identity

設定應用程式架構

在項目目錄中,執行下列動作:

  1. 在文字編輯器中開啟 Program.cs 檔案。
  2. using新增指示詞以包含Azure.Communication.Identity命名空間。
  3. Main更新方法宣告以支援異步程序代碼。

若要開始,請執行下列程式代碼:

using System;
using Azure;
using Azure.Core;
using Azure.Communication.Identity;

namespace AccessTokensQuickstart
{
    class Program
    {
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            Console.WriteLine("Azure Communication Services - Access Tokens Quickstart");

            // Quickstart code goes here
        }
    }
}

驗證用戶端

使用您的 連接字串 初始化CommunicationIdentityClient。 下列程式Main代碼會從名為COMMUNICATION_SERVICES_CONNECTION_STRING的環境變數擷取資源的 連接字串。

如需詳細資訊,請參閱建立和管理通訊服務資源的<儲存您的 連接字串>一節

// This code demonstrates how to retrieve your connection string
// from an environment variable.
string connectionString = Environment.GetEnvironmentVariable("COMMUNICATION_SERVICES_CONNECTION_STRING");
var client = new CommunicationIdentityClient(connectionString);

或者,您可以執行下列程式代碼來分隔端點和存取金鑰:

// This code demonstrates how to fetch your endpoint and access key
// from an environment variable.
string endpoint = Environment.GetEnvironmentVariable("COMMUNICATION_SERVICES_ENDPOINT");
string accessKey = Environment.GetEnvironmentVariable("COMMUNICATION_SERVICES_ACCESSKEY");
var client = new CommunicationIdentityClient(new Uri(endpoint), new AzureKeyCredential(accessKey));

如果您已經設定 Microsoft Entra 應用程式,您可以使用 Microsoft Entra 識別碼進行驗證。

TokenCredential tokenCredential = new DefaultAzureCredential();
var client = new CommunicationIdentityClient(new Uri(endpoint), tokenCredential);

建立身分識別

若要建立存取令牌,您需要身分識別。 Azure 通訊服務 針對此目的維護輕量型身分識別目錄。 createUser使用 方法,在目錄中建立具有唯Id一 的專案。 稍後需要身分識別,才能發行存取令牌。

var identityResponse = await client.CreateUserAsync();
var identity = identityResponse.Value;
Console.WriteLine($"\nCreated an identity with ID: {identity.Id}");

儲存已接收的身分識別,並對應至您應用程式的使用者(例如,將它儲存在您的應用程式伺服器資料庫中)。

發出存取令牌

取得通訊服務身分識別之後,請使用 GetToken 方法來為其發出存取令牌。 參數 scopes 會定義一組存取令牌許可權和角色。 如需詳細資訊,請參閱身分識別模型中支持的動作清單。 您也可以根據 Azure 通訊服務身分識別的字串表示,建構 的新實例 communicationUser

// Issue an access token with a validity of 24 hours and the "voip" scope for an identity
var tokenResponse = await client.GetTokenAsync(identity, scopes: new [] { CommunicationTokenScope.VoIP });

// Get the token from the response
var token =  tokenResponse.Value.Token;
var expiresOn = tokenResponse.Value.ExpiresOn;
Console.WriteLine($"\nIssued an access token with 'voip' scope that expires at {expiresOn}:");
Console.WriteLine(token);

存取令牌是需要重新發出之短期認證。 這樣做可能會導致應用程式用戶體驗中斷。 屬性 expiresOn 表示存取令牌的存留期。

設定自定義令牌到期時間

默認令牌到期時間為24小時,但您可以將值提供給選擇性參數 tokenExpiresIn,以設定它。 要求新的令牌時,建議您為令牌到期時間指定通訊會話的預期一般長度。

// Issue an access token with a validity of an hour and the "voip" scope for an identity 
TimeSpan tokenExpiresIn = TimeSpan.FromHours(1);
CommunicationTokenScope[] scopes = new[] { CommunicationTokenScope.VoIP };
var tokenResponse = await client.GetTokenAsync(identity, scopes, tokenExpiresIn);

在相同的要求中建立身分識別併發出令牌

您可以使用 CreateUserAndTokenAsync 方法來建立通訊服務身分識別,並同時為其發出存取令牌。 參數 scopes 會定義一組存取令牌許可權和角色。 如需詳細資訊,請參閱驗證至 Azure 通訊服務支援的動作清單。

// Issue an identity and an access token with a validity of 24 hours and the "voip" scope for the new identity
var identityAndTokenResponse = await client.CreateUserAndTokenAsync(scopes: new[] { CommunicationTokenScope.VoIP });

// Retrieve the identity, token, and expiration date from the response
var identity = identityAndTokenResponse.Value.User;
var token = identityAndTokenResponse.Value.AccessToken.Token;
var expiresOn = identityAndTokenResponse.Value.AccessToken.ExpiresOn;
Console.WriteLine($"\nCreated an identity with ID: {identity.Id}");
Console.WriteLine($"\nIssued an access token with 'voip' scope that expires at {expiresOn}:");
Console.WriteLine(token);

重新整理存取令牌

若要重新整理存取權杖,請將物件的實體 CommunicationUserIdentifier 傳遞至 GetTokenAsync。 如果您已儲存此專案 Id ,且需要建立新的 CommunicationUserIdentifier,您可以將預存的 Id 建構函式傳遞至建構函式, CommunicationUserIdentifier 如下所示:

var identityToRefresh = new CommunicationUserIdentifier(identity.Id);
var tokenResponse = await client.GetTokenAsync(identityToRefresh, scopes: new [] { CommunicationTokenScope.VoIP });

撤銷存取令牌

您偶爾可能需要明確撤銷存取令牌。 例如,當應用程式使用者變更其用來向服務進行驗證的密碼時,您會這麼做。 方法 RevokeTokensAsync 會使所有發行至身分識別的作用中存取令牌失效。

await client.RevokeTokensAsync(identity);
Console.WriteLine($"\nSuccessfully revoked all access tokens for identity with ID: {identity.Id}");

刪除身分識別

當您刪除身分識別時,您會撤銷所有作用中的存取令牌,並防止進一步發行身分識別的存取令牌。 這樣做也會移除與身分識別相關聯的所有保存內容。

await client.DeleteUserAsync(identity);
Console.WriteLine($"\nDeleted the identity with ID: {identity.Id}");

執行程式碼

當您完成建立存取令牌之後,可以使用 命令從應用程式目錄 dotnet run 執行應用程式。

dotnet run

應用程式的輸出會描述每個已完成的動作:

Azure Communication Services - Access Tokens Quickstart

Created an identity with ID: 8:acs:4ccc92c8-9815-4422-bddc-ceea181dc774_00000006-19e0-2727-80f5-8b3a0d003502

Issued an access token with 'voip' scope that expires at 10/11/2022 7:34:29 AM +00:00:
eyJhbGciOiJSUzI1NiIsImtpZCI6IjEwNiIsIng1dCI6Im9QMWFxQnlfR3hZU3pSaXhuQ25zdE5PU2p2cyIsInR5cCI6IkpXVCJ9.eyJza3lwZWlkIjoiYWNzOjAwMDAwMDAwLTAwMDAtMDAwMC0wMDAwLTAwMDAwMDAwMDAwMF8wMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJzY3AiOjE3OTIsImNzaSI6IjE2NjUzODcyNjkiLCJleHAiOjE2NjUzOTA4NjksImFjc1Njb3BlIjoidm9pcCIsInJlc291cmNlSWQiOiIwMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJyZXNvdXJjZUxvY2F0aW9uIjoidW5pdGVkc3RhdGVzIiwiaWF0IjoxNjY1Mzg3MjY5fQ.kTXpQQtY7w6O82kByljZXrKtBvNNOleDE5m06LapzLeoWfRZCCpJQcDzBoLRA146mOhNzLZ0b5WMNTa5tD-0hWCiicDwgKLMASEGY9g0EvNQOidPff47g2hh6yqi9PKiDPp-t5siBMYqA6Nh6CQ-Oeh-35vcRW09VfcqFN38IgSSzJ7QkqBiY_QtfXz-iaj81Td0287KO4U1y2LJIGiyJLWC567F7A_p1sl6NmPKUmvmwM47tyCcQ1r_lfkRdeyDmcrGgY6yyI3XJZQbpxyt2DZqOTSVPB4PuRl7iyXxvppEa4Uo_y_BdMOOWFe6YTRB5O5lhI8m7Tf0LifisxX2sw

Created an identity with ID: 8:acs:4ccc92c8-9815-4422-bddc-ceea181dc774_00000006-1ce9-31b4-54b7-a43a0d006a52

Issued an access token with 'voip' scope that expires at 10/11/2022 7:34:29 AM +00:00:
eyJhbGciOiJSUzI1NiIsImtpZCI6IjEwNiIsIng1dCI6Im9QMWFxQnlfR3hZU3pSaXhuQ25zdE5PU2p2cyIsInR5cCI6IkpXVCJ9.eyJza3lwZWlkIjoiYWNzOjAwMDAwMDAwLTAwMDAtMDAwMC0wMDAwLTAwMDAwMDAwMDAwMF8wMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJzY3AiOjE3OTIsImNzaSI6IjE2NjUzODcyNjkiLCJleHAiOjE2NjUzOTA4NjksImFjc1Njb3BlIjoidm9pcCIsInJlc291cmNlSWQiOiIwMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJyZXNvdXJjZUxvY2F0aW9uIjoidW5pdGVkc3RhdGVzIiwiaWF0IjoxNjY1Mzg3MjY5fQ.kTXpQQtY7w6O82kByljZXrKtBvNNOleDE5m06LapzLeoWfRZCCpJQcDzBoLRA146mOhNzLZ0b5WMNTa5tD-0hWCiicDwgKLMASEGY9g0EvNQOidPff47g2hh6yqi9PKiDPp-t5siBMYqA6Nh6CQ-Oeh-35vcRW09VfcqFN38IgSSzJ7QkqBiY_QtfXz-iaj81Td0287KO4U1y2LJIGiyJLWC567F7A_p1sl6NmPKUmvmwM47tyCcQ1r_lfkRdeyDmcrGgY6yyI3XJZQbpxyt2DZqOTSVPB4PuRl7iyXxvppEa4Uo_y_BdMOOWFe6YTRB5O5lhI8m7Tf0LifisxX2sw

Successfully revoked all access tokens for identity with ID: 8:acs:4ccc92c8-9815-4422-bddc-ceea181dc774_00000006-19e0-2727-80f5-8b3a0d003502

Deleted the identity with ID: 8:acs:4ccc92c8-9815-4422-bddc-ceea181dc774_00000006-19e0-2727-80f5-8b3a0d003502

必要條件

  • 具有有效訂用帳戶的 Azure 帳戶。 免費建立帳戶
  • Node.js主動 LTS 和維護 LTS 版本(建議使用 8.11.1 和 10.14.1)。
  • 作用中的通訊服務資源和 連接字串。 建立通訊服務資源

最終程式碼

在 GitHub尋找本快速入門的完成程式代碼。

設定您的環境

建立新的 Node.js 應用程式

在終端機或命令提示字元視窗中,為您的應用程式建立新的目錄,然後開啟它。

mkdir access-tokens-quickstart && cd access-tokens-quickstart

執行 npm init -y 以使用預設設定建立 package.json 檔案。

npm init -y

Install the package

npm install使用 命令來安裝適用於 JavaScript 的 Azure 通訊服務 Identity SDK。

npm install @azure/communication-identity@latest --save

選項--save會將連結庫列為package.json檔案中的相依性。

設定應用程式架構

  1. 在項目目錄中建立名為 issue-access-token.js 的檔案,並新增下列程序代碼:

    const { CommunicationIdentityClient } = require('@azure/communication-identity');
    
    const main = async () => {
      console.log("Azure Communication Services - Access Tokens Quickstart")
    
      // Quickstart code goes here
    };
    
    main().catch((error) => {
      console.log("Encountered an error");
      console.log(error);
    })
    

驗證用戶端

使用您的 連接字串 具現化CommunicationIdentityClient。 下列程式Main代碼會從名為COMMUNICATION_SERVICES_CONNECTION_STRING的環境變數擷取資源的 連接字串。

如需詳細資訊,請參閱建立和管理通訊服務資源的<儲存您的 連接字串>一節

// This code demonstrates how to fetch your connection string
// from an environment variable.
const connectionString = process.env['COMMUNICATION_SERVICES_CONNECTION_STRING'];

// Instantiate the identity client
const identityClient = new CommunicationIdentityClient(connectionString);

或者,您可以執行下列程式代碼來分隔端點和存取金鑰:

// This code demonstrates how to fetch your endpoint and access key
// from an environment variable.
const endpoint = process.env["COMMUNICATION_SERVICES_ENDPOINT"];
const accessKey = process.env["COMMUNICATION_SERVICES_ACCESSKEY"];

// Create the credential
const tokenCredential = new AzureKeyCredential(accessKey);

// Instantiate the identity client
const identityClient = new CommunicationIdentityClient(endpoint, tokenCredential)

如果您已經設定 Microsoft Entra 應用程式,您可以使用 Microsoft Entra 識別碼進行驗證。

const endpoint = process.env["COMMUNICATION_SERVICES_ENDPOINT"];
const tokenCredential = new DefaultAzureCredential();
const identityClient = new CommunicationIdentityClient(endpoint, tokenCredential);

建立身分識別

若要建立存取令牌,您需要身分識別。 Azure 通訊服務 針對此目的維護輕量型身分識別目錄。 createUser使用 方法,在目錄中建立具有唯Id一 的專案。 稍後需要身分識別,才能發行存取令牌。

let identityResponse = await identityClient.createUser();
console.log(`\nCreated an identity with ID: ${identityResponse.communicationUserId}`);

儲存已接收的身分識別,並對應至您應用程式的使用者(例如,將它儲存在您的應用程式伺服器資料庫中)。

發出存取令牌

getToken使用方法來發出通訊服務身分識別的存取令牌。 參數 scopes 會定義一組存取令牌許可權和角色。 如需詳細資訊,請參閱身分識別模型中支持的動作清單。 您也可以根據 Azure 通訊服務身分識別的字串表示,建構 的新實例 communicationUser

// Issue an access token with a validity of 24 hours and the "voip" scope for an identity
let tokenResponse = await identityClient.getToken(identityResponse, ["voip"]);

// Get the token and its expiration date from the response
const { token, expiresOn } = tokenResponse;
console.log(`\nIssued an access token with 'voip' scope that expires at ${expiresOn}:`);
console.log(token);

存取令牌是需要重新發出之短期認證。 這樣做可能會導致應用程式用戶體驗中斷。 屬性 expiresOn 表示存取令牌的存留期。

設定自定義令牌到期時間

默認令牌到期時間是 24 小時 (1440 分鐘),但您可以藉由提供介於 60 分鐘到 1440 分鐘之間的值來設定選擇性參數 tokenExpiresInMinutes。 要求新的令牌時,建議您為令牌到期時間指定通訊會話的預期一般長度。

// Issue an access token with a validity of an hour and the "voip" scope for an identity
const tokenOptions: GetTokenOptions = { tokenExpiresInMinutes: 60 };
let tokenResponse = await identityClient.getToken
(identityResponse, ["voip"], tokenOptions);

在一個方法呼叫中建立身分識別併發出令牌

您可以使用 createUserAndToken 方法來建立通訊服務身分識別,並同時為其發出存取令牌。 參數 scopes 會定義一組存取令牌許可權和角色。 同樣地,您會使用 voip 範圍建立它。

// Issue an identity and an access token with a validity of 24 hours and the "voip" scope for the new identity
let identityTokenResponse = await identityClient.createUserAndToken(["voip"]);

// Get the token, its expiration date, and the user from the response
const { token, expiresOn, user } = identityTokenResponse;
console.log(`\nCreated an identity with ID: ${user.communicationUserId}`);
console.log(`\nIssued an access token with 'voip' scope that expires at ${expiresOn}:`);
console.log(token);

重新整理存取令牌

當令牌到期時,您將需要定期重新整理令牌。 重新整理很容易,只要使用用來發出令牌的相同身分識別再次呼叫 getToken 即可。 您也需要提供 scopes 重新整理權杖的 。

// Value of identityResponse represents the Azure Communication Services identity stored during identity creation and then used to issue the tokens being refreshed
let refreshedTokenResponse = await identityClient.getToken(identityResponse, ["voip"]);

撤銷存取令牌

您偶爾可能需要撤銷存取令牌。 例如,當應用程式使用者變更其用來向服務進行驗證的密碼時,您會這麼做。 方法 revokeTokens 會使所有發行至身分識別的作用中存取令牌失效。

await identityClient.revokeTokens(identityResponse);

console.log(`\nSuccessfully revoked all access tokens for identity with ID: ${identityResponse.communicationUserId}`);

刪除身分識別

當您刪除身分識別時,您會撤銷所有作用中的存取令牌,並防止進一步發行身分識別的存取令牌。 這樣做也會移除與身分識別相關聯的所有保存內容。

await identityClient.deleteUser(identityResponse);

console.log(`\nDeleted the identity with ID: ${identityResponse.communicationUserId}`);

執行程式碼

從主控台提示字元,移至包含issue-access-token.js檔案的目錄,然後執行下列node命令以執行應用程式:

node ./issue-access-token.js

應用程式的輸出會描述每個已完成的動作:

Azure Communication Services - Access Tokens Quickstart

Created an identity with ID: 8:acs:4ccc92c8-9815-4422-bddc-ceea181dc774_00000006-19e0-2727-80f5-8b3a0d003502

Issued an access token with 'voip' scope that expires at 2022-10-11T07:34:29.9028648+00:00:
eyJhbGciOiJSUzI1NiIsImtpZCI6IjEwNiIsIng1dCI6Im9QMWFxQnlfR3hZU3pSaXhuQ25zdE5PU2p2cyIsInR5cCI6IkpXVCJ9.eyJza3lwZWlkIjoiYWNzOjAwMDAwMDAwLTAwMDAtMDAwMC0wMDAwLTAwMDAwMDAwMDAwMF8wMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJzY3AiOjE3OTIsImNzaSI6IjE2NjUzODcyNjkiLCJleHAiOjE2NjUzOTA4NjksImFjc1Njb3BlIjoidm9pcCIsInJlc291cmNlSWQiOiIwMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJyZXNvdXJjZUxvY2F0aW9uIjoidW5pdGVkc3RhdGVzIiwiaWF0IjoxNjY1Mzg3MjY5fQ.kTXpQQtY7w6O82kByljZXrKtBvNNOleDE5m06LapzLeoWfRZCCpJQcDzBoLRA146mOhNzLZ0b5WMNTa5tD-0hWCiicDwgKLMASEGY9g0EvNQOidPff47g2hh6yqi9PKiDPp-t5siBMYqA6Nh6CQ-Oeh-35vcRW09VfcqFN38IgSSzJ7QkqBiY_QtfXz-iaj81Td0287KO4U1y2LJIGiyJLWC567F7A_p1sl6NmPKUmvmwM47tyCcQ1r_lfkRdeyDmcrGgY6yyI3XJZQbpxyt2DZqOTSVPB4PuRl7iyXxvppEa4Uo_y_BdMOOWFe6YTRB5O5lhI8m7Tf0LifisxX2sw

Created an identity with ID: 8:acs:4ccc92c8-9815-4422-bddc-ceea181dc774_00000006-1ce9-31b4-54b7-a43a0d006a52

Issued an access token with 'voip' scope that expires at 2022-10-11T07:34:29.9028648+00:00:
eyJhbGciOiJSUzI1NiIsImtpZCI6IjEwNiIsIng1dCI6Im9QMWFxQnlfR3hZU3pSaXhuQ25zdE5PU2p2cyIsInR5cCI6IkpXVCJ9.eyJza3lwZWlkIjoiYWNzOjAwMDAwMDAwLTAwMDAtMDAwMC0wMDAwLTAwMDAwMDAwMDAwMF8wMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJzY3AiOjE3OTIsImNzaSI6IjE2NjUzODcyNjkiLCJleHAiOjE2NjUzOTA4NjksImFjc1Njb3BlIjoidm9pcCIsInJlc291cmNlSWQiOiIwMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJyZXNvdXJjZUxvY2F0aW9uIjoidW5pdGVkc3RhdGVzIiwiaWF0IjoxNjY1Mzg3MjY5fQ.kTXpQQtY7w6O82kByljZXrKtBvNNOleDE5m06LapzLeoWfRZCCpJQcDzBoLRA146mOhNzLZ0b5WMNTa5tD-0hWCiicDwgKLMASEGY9g0EvNQOidPff47g2hh6yqi9PKiDPp-t5siBMYqA6Nh6CQ-Oeh-35vcRW09VfcqFN38IgSSzJ7QkqBiY_QtfXz-iaj81Td0287KO4U1y2LJIGiyJLWC567F7A_p1sl6NmPKUmvmwM47tyCcQ1r_lfkRdeyDmcrGgY6yyI3XJZQbpxyt2DZqOTSVPB4PuRl7iyXxvppEa4Uo_y_BdMOOWFe6YTRB5O5lhI8m7Tf0LifisxX2sw

Successfully revoked all access tokens for identity with ID: 8:acs:4ccc92c8-9815-4422-bddc-ceea181dc774_00000006-19e0-2727-80f5-8b3a0d003502

Deleted the identity with ID: 8:acs:4ccc92c8-9815-4422-bddc-ceea181dc774_00000006-19e0-2727-80f5-8b3a0d003502

必要條件

最終程式碼

在 GitHub尋找本快速入門的完成程式代碼。

設定您的環境

建立新的 Python 應用程式

  1. 在終端機或命令提示字元視窗中,為您的應用程式建立新的目錄,然後開啟它。

    mkdir access-tokens-quickstart && cd access-tokens-quickstart
    
  2. 使用文本編輯器在專案根目錄中建立名為 issue-access-tokens.py 的檔案,並新增程序的結構,包括基本例外狀況處理。 您將在下列各節中,將本快速入門的所有原始程式碼新增至此檔案。

    import os
    from datetime import timedelta
    from azure.communication.identity import CommunicationIdentityClient, CommunicationUserIdentifier
    
    try:
       print("Azure Communication Services - Access Tokens Quickstart")
       # Quickstart code goes here
    except Exception as ex:
       print("Exception:")
       print(ex)
    

Install the package

當您仍在應用程式目錄中時,請使用 pip install 命令安裝 Azure 通訊服務 Identity SDK for Python 套件。

pip install azure-communication-identity

驗證用戶端

使用您的 連接字串 具現化 CommunicationIdentityClient 。 下列程式try代碼會從名為COMMUNICATION_SERVICES_CONNECTION_STRING的環境變數擷取資源的 連接字串。

如需詳細資訊,請參閱建立和管理通訊服務資源的<儲存您的 連接字串>一節

# This code demonstrates how to retrieve your connection string
# from an environment variable.
connection_string = os.environ["COMMUNICATION_SERVICES_CONNECTION_STRING"]

# Instantiate the identity client
client = CommunicationIdentityClient.from_connection_string(connection_string)

或者,如果您已經設定 Microsoft Entra 應用程式,您可以使用 Microsoft Entra 識別符進行驗證。

endpoint = os.environ["COMMUNICATION_SERVICES_ENDPOINT"]
client = CommunicationIdentityClient(endpoint, DefaultAzureCredential())

建立身分識別

若要建立存取令牌,您需要身分識別。 Azure 通訊服務 維護此用途的輕量型身分識別目錄。 create_user使用 方法,在目錄中建立具有唯Id一 的專案。 稍後需要身分識別,才能發行存取令牌。

identity = client.create_user()
print("\nCreated an identity with ID: " + identity.properties['id'])

儲存已接收的身分識別,並對應至您應用程式的使用者(例如,將它儲存在您的應用程式伺服器資料庫中)。

發出存取令牌

get_token使用方法來發出通訊服務身分識別的存取令牌。 參數 scopes 會定義一組存取令牌許可權和角色。 如需詳細資訊,請參閱身分識別模型中支持的動作清單。 您也可以根據 Azure 通訊服務身分識別的字串表示,建構參數 CommunicationUserIdentifier 的新實例。

# Issue an access token with a validity of 24 hours and the "voip" scope for an identity
token_result = client.get_token(identity, ["voip"])
print("\nIssued an access token with 'voip' scope that expires at " + token_result.expires_on + ":")
print(token_result.token)

存取令牌是需要重新發出之短期認證。 這樣做可能會導致應用程式用戶體驗中斷。 expires_on回應屬性表示存取令牌的存留期。

設定自定義令牌到期時間

默認令牌到期時間為24小時,但您可以將值提供給選擇性參數 token_expires_in,以設定它。 要求新的令牌時,建議您為令牌到期時間指定通訊會話的預期一般長度。

# Issue an access token with a validity of an hour and the "voip" scope for an identity
token_expires_in = timedelta(hours=1)
token_result = client.get_token(identity, ["voip"], token_expires_in=token_expires_in)

在相同的要求中建立身分識別併發出存取令牌

您可以使用 create_user_and_token 方法來建立通訊服務身分識別,並同時為其發出存取令牌。 參數 scopes 會定義一組存取令牌許可權和角色。 如需詳細資訊,請參閱驗證至 Azure 通訊服務支援的動作清單。

# Issue an identity and an access token with a validity of 24 hours and the "voip" scope for the new identity
identity_token_result = client.create_user_and_token(["voip"])

# Get the token details from the response
identity = identity_token_result[0]
token = identity_token_result[1].token
expires_on = identity_token_result[1].expires_on
print("\nCreated an identity with ID: " + identity.properties['id'])
print("\nIssued an access token with 'voip' scope that expires at " + expires_on + ":")
print(token)

重新整理存取令牌

若要重新整理存取令牌,請使用 CommunicationUserIdentifier 物件透過傳入現有的身分識別來重新發出令牌:

# The existingIdentity value represents the Communication Services identity that's stored during identity creation
identity = CommunicationUserIdentifier(existingIdentity)
token_result = client.get_token(identity, ["voip"])

撤銷存取令牌

您偶爾可能需要明確撤銷存取令牌。 例如,當應用程式使用者變更其用來向服務進行驗證的密碼時,您會這麼做。 方法 revoke_tokens 會使所有發行至身分識別的作用中存取令牌失效。

client.revoke_tokens(identity)
print("\nSuccessfully revoked all access tokens for identity with ID: " + identity.properties['id'])

刪除身分識別

當您刪除身分識別時,您會撤銷所有作用中的存取令牌,並防止進一步發行身分識別的存取令牌。 這樣做也會移除與身分識別相關聯的所有保存內容。

client.delete_user(identity)
print("\nDeleted the identity with ID: " + identity.properties['id'])

執行程式碼

從主控台提示字元,移至包含 issue-access-tokens.py 檔案的目錄,然後執行下列python命令來執行應用程式。

python ./issue-access-tokens.py

應用程式的輸出會描述每個已完成的動作:

Azure Communication Services - Access Tokens Quickstart

Created an identity with ID: 8:acs:4ccc92c8-9815-4422-bddc-ceea181dc774_00000006-19e0-2727-80f5-8b3a0d003502

Issued an access token with 'voip' scope that expires at 2022-10-11T07:34:29.9028648+00:00:
eyJhbGciOiJSUzI1NiIsImtpZCI6IjEwNiIsIng1dCI6Im9QMWFxQnlfR3hZU3pSaXhuQ25zdE5PU2p2cyIsInR5cCI6IkpXVCJ9.eyJza3lwZWlkIjoiYWNzOjAwMDAwMDAwLTAwMDAtMDAwMC0wMDAwLTAwMDAwMDAwMDAwMF8wMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJzY3AiOjE3OTIsImNzaSI6IjE2NjUzODcyNjkiLCJleHAiOjE2NjUzOTA4NjksImFjc1Njb3BlIjoidm9pcCIsInJlc291cmNlSWQiOiIwMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJyZXNvdXJjZUxvY2F0aW9uIjoidW5pdGVkc3RhdGVzIiwiaWF0IjoxNjY1Mzg3MjY5fQ.kTXpQQtY7w6O82kByljZXrKtBvNNOleDE5m06LapzLeoWfRZCCpJQcDzBoLRA146mOhNzLZ0b5WMNTa5tD-0hWCiicDwgKLMASEGY9g0EvNQOidPff47g2hh6yqi9PKiDPp-t5siBMYqA6Nh6CQ-Oeh-35vcRW09VfcqFN38IgSSzJ7QkqBiY_QtfXz-iaj81Td0287KO4U1y2LJIGiyJLWC567F7A_p1sl6NmPKUmvmwM47tyCcQ1r_lfkRdeyDmcrGgY6yyI3XJZQbpxyt2DZqOTSVPB4PuRl7iyXxvppEa4Uo_y_BdMOOWFe6YTRB5O5lhI8m7Tf0LifisxX2sw

Created an identity with ID: 8:acs:4ccc92c8-9815-4422-bddc-ceea181dc774_00000006-1ce9-31b4-54b7-a43a0d006a52

Issued an access token with 'voip' scope that expires at 2022-10-11T07:34:29.9028648+00:00:
eyJhbGciOiJSUzI1NiIsImtpZCI6IjEwNiIsIng1dCI6Im9QMWFxQnlfR3hZU3pSaXhuQ25zdE5PU2p2cyIsInR5cCI6IkpXVCJ9.eyJza3lwZWlkIjoiYWNzOjAwMDAwMDAwLTAwMDAtMDAwMC0wMDAwLTAwMDAwMDAwMDAwMF8wMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJzY3AiOjE3OTIsImNzaSI6IjE2NjUzODcyNjkiLCJleHAiOjE2NjUzOTA4NjksImFjc1Njb3BlIjoidm9pcCIsInJlc291cmNlSWQiOiIwMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJyZXNvdXJjZUxvY2F0aW9uIjoidW5pdGVkc3RhdGVzIiwiaWF0IjoxNjY1Mzg3MjY5fQ.kTXpQQtY7w6O82kByljZXrKtBvNNOleDE5m06LapzLeoWfRZCCpJQcDzBoLRA146mOhNzLZ0b5WMNTa5tD-0hWCiicDwgKLMASEGY9g0EvNQOidPff47g2hh6yqi9PKiDPp-t5siBMYqA6Nh6CQ-Oeh-35vcRW09VfcqFN38IgSSzJ7QkqBiY_QtfXz-iaj81Td0287KO4U1y2LJIGiyJLWC567F7A_p1sl6NmPKUmvmwM47tyCcQ1r_lfkRdeyDmcrGgY6yyI3XJZQbpxyt2DZqOTSVPB4PuRl7iyXxvppEa4Uo_y_BdMOOWFe6YTRB5O5lhI8m7Tf0LifisxX2sw

Successfully revoked all access tokens for identity with ID: 8:acs:4ccc92c8-9815-4422-bddc-ceea181dc774_00000006-19e0-2727-80f5-8b3a0d003502

Deleted the identity with ID: 8:acs:4ccc92c8-9815-4422-bddc-ceea181dc774_00000006-19e0-2727-80f5-8b3a0d003502

必要條件

最終程式碼

在 GitHub尋找本快速入門的完成程式代碼。

設定您的環境

建立新的 Java 應用程式

在終端機或命令提示字元視窗中,移至您要建立 Java 應用程式的目錄。 若要從 maven-archetype-quickstart 範本產生 Java 專案,請執行下列程式代碼:

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

您會發現工作 generate 會建立與 相同名稱 artifactId的目錄。 在此目錄下, src/main/java 目錄包含專案原始碼、 src/test/java 目錄包含測試來源,而 pom.xml 檔案是專案的 Project 物件模型或 POM。 此檔案用於專案組態參數。

安裝通訊服務套件

在文字編輯器中開啟 pom.xml 檔案。 將下列相依性元素新增至相依性群組:

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-communication-identity</artifactId>
    <version>[1.4.0,)</version>
</dependency>

此程式代碼會指示 Maven 安裝通訊服務識別 SDK,以供稍後使用。

設定應用程式架構

在項目目錄中,執行下列動作:

  1. 移至 /src/main/java/com/communication/quickstart 目錄。
  2. 編輯器中開啟App.java 檔案。
  3. System.out.println("Hello world!");取代語句。
  4. 新增 import 指示詞。

使用下列程式代碼開始:

package com.communication.quickstart;

import com.azure.communication.common.*;
import com.azure.communication.identity.*;
import com.azure.communication.identity.models.*;
import com.azure.core.credential.*;

import java.io.IOException;
import java.time.*;
import java.util.*;

public class App
{
    public static void main( String[] args ) throws IOException
    {
        System.out.println("Azure Communication Services - Access Tokens Quickstart");
        // Quickstart code goes here
    }
}

驗證用戶端

使用資源的存取金鑰和端點具現化 CommunicationIdentityClient 。 如需詳細資訊,請參閱建立和管理通訊服務資源的<儲存您的 連接字串>一節

此外,您可以使用任何實作 介面的 com.azure.core.http.HttpClient 自訂 HTTP 用戶端來初始化用戶端。

在 App.java 檔案中,將下列程式代碼新增至 main 方法:

// You can find your endpoint and access key from your resource in the Azure portal
String endpoint = "https://<RESOURCE_NAME>.communication.azure.com";
String accessKey = "SECRET";

CommunicationIdentityClient communicationIdentityClient = new CommunicationIdentityClientBuilder()
        .endpoint(endpoint)
        .credential(new AzureKeyCredential(accessKey))
        .buildClient();

您可以使用 方法來提供整個 連接字串connectionString(),而不是提供端點和存取密鑰。

// You can find your connection string from your Communication Services resource in the Azure portal
String connectionString = "<connection_string>";

CommunicationIdentityClient communicationIdentityClient = new CommunicationIdentityClientBuilder()
    .connectionString(connectionString)
    .buildClient();

如果您已經設定 Microsoft Entra 應用程式,您可以使用 Microsoft Entra 識別碼進行驗證。

String endpoint = "https://<RESOURCE_NAME>.communication.azure.com";
TokenCredential credential = new DefaultAzureCredentialBuilder().build();

CommunicationIdentityClient communicationIdentityClient = new CommunicationIdentityClientBuilder()
        .endpoint(endpoint)
        .credential(credential)
        .buildClient();

建立身分識別

若要建立存取令牌,您需要身分識別。 Azure 通訊服務 為此用途維護輕量型身分識別目錄。 createUser使用 方法,在目錄中建立具有唯Id一 的專案。

CommunicationUserIdentifier user = communicationIdentityClient.createUser();
System.out.println("\nCreated an identity with ID: " + user.getId());

稍後需要建立的身分識別,才能發出存取令牌。 儲存已接收的身分識別,並對應至您應用程式的使用者(例如,將它儲存在您的應用程式伺服器資料庫中)。

發出存取令牌

getToken使用方法來發出通訊服務身分識別的存取令牌。 參數 scopes 會定義一組存取令牌許可權和角色。 如需詳細資訊,請參閱身分識別模型中支持的動作清單。

在下列程式代碼中,使用您在上一個步驟中建立的用戶變數來取得令牌。

// Issue an access token with a validity of 24 hours and the "voip" scope for a user identity
List<CommunicationTokenScope> scopes = new ArrayList<>(Arrays.asList(CommunicationTokenScope.VOIP));
AccessToken accessToken = communicationIdentityClient.getToken(user, scopes);
OffsetDateTime expiresAt = accessToken.getExpiresAt();
String token = accessToken.getToken();
System.out.println("\nIssued an access token with 'voip' scope that expires at: " + expiresAt + ": " + token);

存取令牌是需要重新發出之短期認證。 這樣做可能會導致應用程式用戶體驗中斷。 屬性 expiresAt 表示存取令牌的存留期。

設定自定義令牌到期時間

默認令牌到期時間為24小時,但您可以將值提供給選擇性參數 tokenExpiresIn,以設定它。 要求新的令牌時,建議您為令牌到期時間指定通訊會話的預期一般長度。

// Issue an access token with a validity of an hour and the "voip" scope for a user identity
List<CommunicationTokenScope> scopes = new ArrayList<>(Arrays.asList(CommunicationTokenScope.VOIP));
Duration tokenExpiresIn = Duration.ofHours(1);
AccessToken accessToken = communicationIdentityClient.getToken(user, scopes, tokenExpiresIn);

在一個要求中建立身分識別併發出令牌

或者,您可以使用 'createUserAndToken' 方法來在目錄中建立具有唯一的新 Id 專案,同時發出存取令牌。

//Create an identity and issue token with a validity of 24 hours in one call
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
CommunicationUserIdentifierAndToken result = communicationIdentityClient.createUserAndToken(scopes);
CommunicationUserIdentifier user = result.getUser();
System.out.println("\nCreated a user identity with ID: " + user.getId());
AccessToken accessToken = result.getUserToken();
OffsetDateTime expiresAt = accessToken.getExpiresAt();
String token = accessToken.getToken();
System.out.println("\nIssued an access token with 'chat' scope that expires at: " + expiresAt + ": " + token);

重新整理存取令牌

若要重新整理存取令牌,請使用 CommunicationUserIdentifier 物件重新發出它:

// existingIdentity represents the Communication Services identity that's stored during identity creation
CommunicationUserIdentifier identity = new CommunicationUserIdentifier(existingIdentity.getId());
AccessToken response = communicationIdentityClient.getToken(identity, scopes);

撤銷存取令牌

您偶爾可能需要明確撤銷存取令牌。 例如,當應用程式使用者變更其用來向服務進行驗證的密碼時,您會這麼做。 方法 revokeTokens 會使特定使用者的所有作用中存取令牌失效。 在下列程式代碼中,您可以使用先前建立的使用者。

communicationIdentityClient.revokeTokens(user);
System.out.println("\nSuccessfully revoked all access tokens for user identity with ID: " + user.getId());

刪除身分識別

當您刪除身分識別時,您會撤銷所有作用中的存取令牌,並防止進一步發行身分識別的存取令牌。 這樣做也會移除與身分識別相關聯的所有保存內容。

communicationIdentityClient.deleteUser(user);
System.out.println("\nDeleted the user identity with ID: " + user.getId());

執行程式碼

移至包含pom.xml檔案的目錄,然後使用下列mvn命令編譯專案:

mvn compile

然後,建置套件:

mvn package

執行下列 mvn 命令以執行應用程式:

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

應用程式的輸出會描述每個已完成的動作:

Azure Communication Services - Access Tokens Quickstart

Created an identity with ID: 8:acs:4ccc92c8-9815-4422-bddc-ceea181dc774_00000006-19e0-2727-80f5-8b3a0d003502

Issued an access token with 'voip' scope that expires at 2022-10-11T07:34:29.902864800Z:
eyJhbGciOiJSUzI1NiIsImtpZCI6IjEwNiIsIng1dCI6Im9QMWFxQnlfR3hZU3pSaXhuQ25zdE5PU2p2cyIsInR5cCI6IkpXVCJ9.eyJza3lwZWlkIjoiYWNzOjAwMDAwMDAwLTAwMDAtMDAwMC0wMDAwLTAwMDAwMDAwMDAwMF8wMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJzY3AiOjE3OTIsImNzaSI6IjE2NjUzODcyNjkiLCJleHAiOjE2NjUzOTA4NjksImFjc1Njb3BlIjoidm9pcCIsInJlc291cmNlSWQiOiIwMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJyZXNvdXJjZUxvY2F0aW9uIjoidW5pdGVkc3RhdGVzIiwiaWF0IjoxNjY1Mzg3MjY5fQ.kTXpQQtY7w6O82kByljZXrKtBvNNOleDE5m06LapzLeoWfRZCCpJQcDzBoLRA146mOhNzLZ0b5WMNTa5tD-0hWCiicDwgKLMASEGY9g0EvNQOidPff47g2hh6yqi9PKiDPp-t5siBMYqA6Nh6CQ-Oeh-35vcRW09VfcqFN38IgSSzJ7QkqBiY_QtfXz-iaj81Td0287KO4U1y2LJIGiyJLWC567F7A_p1sl6NmPKUmvmwM47tyCcQ1r_lfkRdeyDmcrGgY6yyI3XJZQbpxyt2DZqOTSVPB4PuRl7iyXxvppEa4Uo_y_BdMOOWFe6YTRB5O5lhI8m7Tf0LifisxX2sw

Created an identity with ID: 8:acs:4ccc92c8-9815-4422-bddc-ceea181dc774_00000006-1ce9-31b4-54b7-a43a0d006a52

Issued an access token with 'chat' scope that expires at 2022-10-11T07:34:29.902864800Z:
eyJhbGciOiJSUzI1NiIsImtpZCI6IjEwNiIsIng1dCI6Im9QMWFxQnlfR3hZU3pSaXhuQ25zdE5PU2p2cyIsInR5cCI6IkpXVCJ9.eyJza3lwZWlkIjoiYWNzOjAwMDAwMDAwLTAwMDAtMDAwMC0wMDAwLTAwMDAwMDAwMDAwMF8wMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJzY3AiOjE3OTIsImNzaSI6IjE2NjUzODcyNjkiLCJleHAiOjE2NjUzOTA4NjksImFjc1Njb3BlIjoidm9pcCIsInJlc291cmNlSWQiOiIwMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJyZXNvdXJjZUxvY2F0aW9uIjoidW5pdGVkc3RhdGVzIiwiaWF0IjoxNjY1Mzg3MjY5fQ.kTXpQQtY7w6O82kByljZXrKtBvNNOleDE5m06LapzLeoWfRZCCpJQcDzBoLRA146mOhNzLZ0b5WMNTa5tD-0hWCiicDwgKLMASEGY9g0EvNQOidPff47g2hh6yqi9PKiDPp-t5siBMYqA6Nh6CQ-Oeh-35vcRW09VfcqFN38IgSSzJ7QkqBiY_QtfXz-iaj81Td0287KO4U1y2LJIGiyJLWC567F7A_p1sl6NmPKUmvmwM47tyCcQ1r_lfkRdeyDmcrGgY6yyI3XJZQbpxyt2DZqOTSVPB4PuRl7iyXxvppEa4Uo_y_BdMOOWFe6YTRB5O5lhI8m7Tf0LifisxX2sw

Successfully revoked all access tokens for identity with ID: 8:acs:4ccc92c8-9815-4422-bddc-ceea181dc774_00000006-19e0-2727-80f5-8b3a0d003502

Deleted the identity with ID: 8:acs:4ccc92c8-9815-4422-bddc-ceea181dc774_00000006-19e0-2727-80f5-8b3a0d003502

必要條件

建立存取令牌

Azure 入口網站 中,流覽至通訊服務資源內的 [身分識別與使用者存取令牌] 刀鋒視窗。

選擇存取令牌的範圍。 您可以選取 [無]、[一或多個]。 按一下 [產生]

選取身分識別和存取令牌的範圍。

您會看到產生的身分識別和對應的使用者存取令牌。 您可以複製這些字串,並在範例應用程式和其他測試案例中使用它們。

系統會產生身分識別和存取令牌,並顯示到期日。

必要條件

  • 具有作用中訂用帳戶的 Azure 帳戶,或 免費建立 Azure 帳戶。

  • 作用中 Azure 通訊服務 資源,或建立通訊服務資源

  • 作用中的 Azure Logic Apps 資源(邏輯應用程式),或使用 您想要使用的觸發程式建立取用邏輯應用程式工作流程。 目前,Azure 通訊服務 身分識別連接器只提供動作,因此您的邏輯應用程式至少需要觸發程式。

建立使用者

使用 Azure 通訊服務 身分識別連接器在工作流程中新增步驟,請遵循 Power Automate 中的這些步驟,並在編輯模式中開啟 Power Automate 流程。

  1. 在設計工具上,在您要新增動作的步驟下,選取 [新增步驟]。 或者,若要在步驟之間新增動作,請將指標移至這些步驟之間的箭號上方,選取加號 (+),然後選取 [新增動作]。

  2. 在 [選擇作業搜尋] 方塊中,輸入通訊服務身分識別。 從動作清單中,選取 [建立使用者]。

    顯示 Azure 通訊服務 身分識別連接器建立用戶動作的螢幕快照。

  3. 提供 連線 字串。 這可在 Microsoft Azure 的 Azure 中,於 Azure 通訊服務資源內,於左側功能表>的 [金鑰] 選項上找到,連線 ion String

    顯示 Azure 通訊服務 資源內 [金鑰] 頁面的螢幕快照。

  4. 提供 連線 名稱

  5. 按一下 [建立]

    此動作會輸出使用者識別碼,也就是通訊服務使用者身分識別。 此外,如果您按兩下 [顯示進階選項],然後選取 [令牌範圍],動作也會輸出存取令牌及其具有指定範圍的到期時間。

    顯示 Azure 通訊服務 連接器建立用戶動作的螢幕快照。

    顯示 Azure 通訊服務 連接器建立用戶動作進階選項的螢幕快照。

發出使用者存取令牌

擁有通訊服務身分識別之後,您可以使用發出使用者存取令牌動作來發出存取令牌。 下列步驟將示範如何:

  1. 新增動作,並在搜尋方塊中輸入通訊服務身分識別。 從動作清單中,選取 [發出使用者存取令牌]。

    顯示 Azure 通訊服務 身分識別連接器發出存取令牌動作的螢幕快照。

  2. 然後,您可以使用上 一個建立使用者 步驟中的使用者識別碼輸出。

  3. 指定令牌範圍:VoIP 或聊天。 深入瞭解令牌和驗證

    顯示 Azure 通訊服務 身分識別連接器發出存取令牌動作的螢幕快照,指定令牌範圍。

這會輸出具有指定範圍的存取令牌及其到期時間。

撤銷使用者存取令牌

擁有通訊服務身分識別之後,您可以使用發出使用者存取令牌動作來撤銷存取令牌。 下列步驟將示範如何:

  1. 新增動作,並在搜尋方塊中輸入通訊服務身分識別。 從動作清單中,選取 [撤銷使用者存取令牌]。

    顯示 Azure 通訊服務 身分識別連接器撤銷存取令牌動作的螢幕快照。

  2. 指定使用者識別碼

    顯示 Azure 通訊服務 身分識別連接器撤銷存取令牌動作輸入的螢幕快照。

這會撤銷指定之使用者的所有使用者存取令牌,此動作沒有輸出。

刪除使用者

擁有通訊服務身分識別之後,您可以使用發出使用者存取權杖動作來刪除存取權杖 。 下列步驟將示範如何:

  1. 新增動作,並在搜尋方塊中輸入通訊服務身分識別。 從動作清單中,選取 [刪除使用者]。

    顯示 Azure 通訊服務 身分識別連接器 [刪除使用者] 動作的螢幕快照。

  2. 指定使用者識別碼

    顯示 Azure 通訊服務 身分識別連接器刪除使用者動作輸入的螢幕快照。

    這會移除使用者,並撤銷指定使用者的所有使用者存取令牌,此動作沒有任何輸出。

測試邏輯應用程式

若要手動啟動工作流程,請在設計工具工具列上選取 [ 執行]。 工作流程應該建立使用者、為該使用者發出存取令牌,然後將其移除並刪除使用者。 如需詳細資訊,請檢閱 如何執行工作流程。 您可以在工作流程順利執行之後檢查這些動作的輸出。

使用身分識別進行監視和計量

用戶標識碼是做為透過 Azure 監視器收集的記錄和計量的主要密鑰。 例如,若要檢視所有使用者的呼叫,您可以設定驗證的方式,將特定 Azure 通訊服務 身分識別(或身分識別)對應至單一使用者。

深入瞭解 驗證概念、透過 記錄分析呼叫診斷,以及 可供您使用的 計量。

清除資源

若要清除和移除通訊服務訂用帳戶,請刪除資源或資源群組。 刪除資源群組也會刪除與其相關聯的任何其他資源。 如需詳細資訊,請參閱建立和管理通訊服務資源的一節

若要清除邏輯應用程式工作流程和相關資源,請檢閱 如何清除 Azure Logic Apps 資源

下一步

在本快速入門中,您已了解如何:

  • 發出存取令牌
  • 管理身分識別

您可能也想要:

下一步

在本快速入門中,您已瞭解如何建立使用者、刪除使用者、發出使用者存取令牌,以及使用 Azure 通訊服務 Identity 連接器移除使用者存取令牌。 若要深入瞭解,請參閱 Azure 通訊服務 身分識別 連線 檔

若要查看其他連接器如何使用令牌,請參閱如何使用 Azure 通訊服務 從Power Automate 傳送聊天訊息

若要深入瞭解如何使用 Azure 通訊服務 電子郵件連接器傳送電子郵件,請參閱使用 Azure 通訊服務 在Power Automate 中傳送電子郵件訊息。