分享方式:


建立和管理終端使用者的存取令牌

存取權杖可作為特定身分識別,讓 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。

業務

建立身分識別

若要建立存取權杖,您需要有身分識別。 為此,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 命令為 Teams 使用者核發可與 Azure 通訊服務 SDK 搭配使用的存取權杖。

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

取代程式碼中的下列內容:

  • <yourConnectionString> 取代為您的連接字串。
  • <yourAadUser> 取代為您的 Microsoft Entra userId。
  • <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# 應用程式

  1. 在命令提示字元視窗 (例如 cmd、PowerShell 或 Bash) 中,執行 dotnet new 命令以建立名為 AccessTokensQuickstart 的新主控台應用程式。 此命令會建立簡單的 "Hello World" C# 專案,內含單一來源檔案:Program.cs

    dotnet new console -o AccessTokensQuickstart
    
  2. 將您的目錄變更為新建立的應用程式資料夾,然後使用 dotnet build 命令來編譯您的應用程式。

    cd AccessTokensQuickstart
    dotnet build
    

    簡單的 Hello World 輸出隨即顯示。 如果顯示正確,您的設定就會正常運作,而且您可以開始撰寫 Azure 通訊服務程式碼。

安裝套件

在仍位於應用程式目錄時,使用 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 ID 進行驗證

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

儲存所接收到、與應用程式使用者對應的身分識別 (例如,將身分識別儲存到應用程式的伺服器資料庫)。

(預覽)使用相關聯的自訂 ID 建立身分

這很重要

這項功能從 SDK 版本 1.4.0-beta1開始提供。

備註

此功能目前為預覽狀態。

您可以建立與相關聯的 customId 身分識別,以將應用程式的使用者身分識別與 Azure 通訊服務身分識別對應。 如果您再次使用相同的 CreateUser 呼叫 customId 方法,則會返回相同的 user.Id。 這樣就不需要自行儲存對應。

Response<CommunicationUserIdentifier> user = await client.CreateUserAsync(customId: "alice@contoso.com");
Console.WriteLine($"\nCreated an identity with ID: {user.Id}");

(預覽)取得身分識別詳細數據

這很重要

這項功能從 SDK 版本 1.4.0-beta1開始提供。

備註

此功能目前為預覽狀態。

您可以使用 GetUserDetail 方法來擷取使用者的相關信息,包括 customIdlastTokenIssuedAt

Response<CommunicationUserIdentifier> user = await client.CreateUserAsync(customId: "alice@contoso.com");
var userDetails = client.GetUserDetail(user);
Console.WriteLine($"User ID: {userDetails.Id}");
Console.WriteLine($"Custom ID: {userDetails.CustomId}");
Console.WriteLine($"Last token issued at: {userDetails.LastTokenIssuedAt}");

核發存取權杖

擁有通訊服務識別後,請使用 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 提供 1 到 24 小時的值來設定到期時間。 在要求新權杖時,請指定通訊工作階段一般會有的時間長度來作為權杖到期時間。

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

(預覽)在同一請求中使用自定義身份建立和辨識並發出令牌

這很重要

這項功能從 SDK 版本 1.4.0-beta1開始提供。

備註

此功能目前為預覽狀態。

您可以將自定義標識碼傳遞至 CreateUserAndTokenAsync 方法,以建立身分識別,並在單一呼叫中發出存取令牌。

// Issue an identity and an access token with a validity of 24 hours and the "voip" scope for the new identity
Response<CommunicationUserIdentifierAndToken> identityAndTokenResponse = await client.CreateUserAndTokenAsync(customId: "bob@contoso.com", scopes: new[] { CommunicationTokenScope.VoIP });

// Retrieve the identity, token, and expiration date from the response
var identity = identityAndTokenResponse.User;
var token = identityAndTokenResponse.AccessToken.Token;
var expiresOn = identityAndTokenResponse.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

先決條件

最終程式碼

GitHub 尋找完成的程式碼。

設定您的環境

建立新的 Node.js 應用程式

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

    mkdir access-tokens-quickstart && cd access-tokens-quickstart
    
  2. 執行 npm init -y 以使用預設設定建立 package.json 檔案。

    npm init -y
    

安裝套件

使用 npm install 命令安裝適用於 JavaScript 的 Azure 通訊服務識別 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 ID 進行驗證

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

儲存所接收到、與應用程式的使用者對應的身分識別 (例如,將身分識別儲存到應用程式的伺服器資料庫)。

(預覽) 建立具有相關聯自訂識別碼的身分識別

這很重要

這項功能從 SDK 版本 1.4.0-beta1開始提供。

備註

此功能目前為預覽狀態。

您可以使用相關聯的 customId 來建立身分識別,以將應用程式的使用者身分識別對應至 Azure 通訊服務身分識別。 當您以相同的createUser呼叫customId時,服務會傳回相同的communicationUserId。 這樣就不需要自行儲存對應。

const customId = "alice@contoso.com";
let user = await identityClient.createUser({ customId });
console.log(`\nCreated an identity with ID: ${user.communicationUserId}`);

(預覽)取得身分識別詳細數據

這很重要

這項功能從 SDK 版本 1.4.0-beta1開始提供。

備註

此功能目前為預覽狀態。

您可以使用 getUserDetail 方法來擷取使用者的相關信息,包括 customIdlastTokenIssuedAt

const customId = "alice@contoso.com";
let user = await identityClient.createUser({ customId });
let userDetails = client.getUserDetail(user);
console.log(`\nUser ID: ${user.communicationUserId}`);
console.log(`\nCustom ID: ${userDetails.customId}`);
console.log(`\nLast token issued at: ${userDetails.lastTokenIssuedAt}`);

核發存取權杖

請使用 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 分鐘),但您可以為選擇性參數 tokenExpiresInMinutes 提供 60 到 1440 分鐘的值來設定到期時間。 在要求新權杖時,請指定通訊工作階段一般會有的時間長度來作為權杖到期時間。

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

(預覽) 在一個方法呼叫中建立身分識別併發出權杖,包括 customId

這很重要

這項功能從 SDK 版本 1.4.0-beta1開始提供。

備註

此功能目前為預覽狀態。

您可以將自定義標識碼傳遞至 createUserAndToken 方法,以建立身分識別,並在單一呼叫中發出存取令牌。

// Issue an identity and an access token with a validity of 24 hours and the "voip" scope for the new identity
const customId = "bob@contoso.com";
let identityTokenResponse = await identityClient.createUserAndToken(["voip"], { customId });

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

安裝套件

在應用程式目錄中,使用 pip install 命令安裝適用於 Python 套件的 Azure 通訊服務識別 SDK。

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 ID 進行驗證

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 提供 1 到 24 小時的值來設定到期時間。 在要求新權杖時,請指定通訊工作階段一般會有的時間長度來作為權杖到期時間。

# 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 檔案是專案的「專案物件模型」(簡稱 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 ID 進行驗證

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 提供 1 到 24 小時的值來設定到期時間。 在要求新權杖時,請指定通訊工作階段一般會有的時間長度來作為權杖到期時間。

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

執行程式碼

  1. 移至包含 pom.xml 檔案的目錄。

  2. 使用下列 mvn 命令編譯專案:

    mvn compile
    
  3. 建置套件:

    mvn package
    
  4. 執行下列 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

先決條件

建立存取權杖

  1. Azure 入口網站中,瀏覽至通訊服務資源中的 [身分識別與使用者存取權杖] 刀鋒視窗。

  2. 選擇存取權杖的範圍。 您可以選擇無、一或多個服務。

  3. 選取 [產生]

    顯示您選取 [產生] 之身分識別與存取權杖範圍的螢幕擷取畫面。

    系統會產生身分識別和對應的使用者存取權杖。

  4. 複製這些字串,並在範例應用程式和其他測試案例中使用它們。

    顯示具有到期日之身分識別與存取權杖的螢幕擷取畫面

先決條件

建立使用者

使用 Azure 通訊服務識別連接器在工作流程中新增步驟。 在 Power Automate 中完成這些步驟,並在「編輯」模式中開啟 Power Automate 流程。

  1. 開啟設計工具。 在要新增動作的步驟底中,選取 [新增步驟]。 或者,若要在步驟之間新增動作,請將滑鼠暫留在這些步驟之間的箭號上、選取加號 (+),然後選取 [新增動作]

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

    顯示 Azure 通訊服務識別連接器 [建立使用者] 動作的螢幕擷取畫面。

  3. 提供連接字串。 您可以在 Azure 通訊服務資源內的 Microsoft Azure 入口網站中找到它。 選取左側面板功能表中的 [金鑰] 選項,以檢視 [連接字串]。

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

  4. 提供連線名稱。

  5. 按一下 [建立]

    此動作會產生使用者識別碼,也就是通訊服務使用者身分識別。 此外,如果您按一下 [顯示進階選項] 並選取 [權杖範圍],動作也會產生存取權杖及其具有指定範圍的到期時間。

    顯示 Azure 通訊服務連接器 [建立使用者] 動作的螢幕擷取畫面。

    顯示 Azure 通訊服務連接器 [建立使用者] 動作進階選項的螢幕擷取畫面。

核發使用者存取權杖

取得通訊服務識別之後,您可以發出存取權杖。 完成下列步驟:

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

    顯示 Azure 通訊服務識別連接器發出存取權杖動作的螢幕擷取畫面。

  2. 現在,您可以使用先前的建立使用者步驟所得到的使用者識別碼輸出。

  3. 指定權杖範圍:VoIP聊天深入了解權杖和驗證

    螢幕擷取畫面顯示 Azure 通訊服務識別連接器發出存取權杖動作,並指定權杖範圍。

系統會產生存取權杖及其具有指定範圍的到期時間。

撤銷使用者存取權杖

擁有通訊服務識別後,您可以使用「核發使用者存取權杖」動作來撤銷存取權杖。 完成下列步驟:

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

    顯示 Azure 通訊服務識別連接器撤銷存取權杖動作的螢幕擷取畫面。

  2. 指定使用者識別碼。

    顯示 Azure 通訊服務識別連接器撤銷存取權杖動作輸入的螢幕擷取畫面。

系統會撤銷所指定使用者的所有使用者存取權杖,此動作沒有任何輸出。

刪除使用者

擁有通訊服務識別後,您可以使用「核發使用者存取權杖」動作來刪除存取權杖。 完成下列步驟:

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

    顯示 Azure 通訊服務識別連接器 [刪除使用者] 動作的螢幕擷取畫面。

  2. 指定使用者識別碼。

    顯示 Azure 通訊服務識別連接器 [刪除使用者] 動作輸入的螢幕擷取畫面。

系統會移除使用者,並撤銷所指定使用者的所有使用者存取權杖,此動作沒有任何輸出。

測試應用程式邏輯

若要手動啟動工作流程,請從設計工具的工具列,選取 [執行]。 工作流程會建立使用者、為該使用者核發存取權杖,然後移除它並刪除該使用者。

如需詳細資訊,請參閱如何執行工作流程。 工作流程成功執行後,您可以檢查這些動作的輸出。

針對監視和計量使用身分識別

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

如需詳細資訊,請參閱:

清除資源

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

若要清除邏輯應用程式工作流程和相關資源,請參閱使用 Azure 入口網站 > 清除資源建立範例取用邏輯應用程式工作流程

後續步驟

本文說明如何建立使用者及刪除使用者。 它也描述如何使用 Azure 通訊服務識別連接器,對使用者發出存取權杖,以及移除使用者存取權杖。 如需詳細資訊,請參閱Azure 通訊服務識別連接器

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

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