빠른 시작: 액세스 토큰 만들기 및 관리

액세스 토큰을 사용하면 Azure Communication Services SDK가 Azure Communication Services에 대해 특정 ID로 직접 인증할 수 있습니다. 사용자가 애플리케이션 내에서 통화 또는 채팅 스레드에 참여하도록 하려면 액세스 토큰을 만들어야 합니다.

이 빠른 시작에서는 Azure Communication Services SDK를 사용하여 ID를 만들고 액세스 토큰을 관리하는 방법을 알아봅니다. 프로덕션 사용 사례의 경우 서버 쪽 서비스에서 액세스 토큰을 생성하는 것이 좋습니다.

필수 조건

설정

확장 추가

az extension 명령을 사용하여 Azure CLI에 대한 Azure Communication Services 확장을 추가합니다.

az extension add --name communication

Azure CLI에 로그인

Azure CLI에 로그인해야 합니다. 터미널에서 az login 명령을 실행하고 자격 증명을 제공하여 로그인할 수 있습니다.

(선택 사항) 연결 문자열을 전달하지 않고 Azure CLI ID 작업 사용

--connection_string을 사용하여 연결 문자열을 제공할 필요 없이 Azure CLI ID 작업을 사용하도록 AZURE_COMMUNICATION_CONNECTION_STRING 환경 변수를 구성할 수 있습니다. 환경 변수를 구성하려면 콘솔 창을 열고 아래 탭에서 운영 체제를 선택합니다. <yourConnectionString>을 실제 연결 문자열로 바꿉니다.

콘솔 창을 열고 다음 명령을 입력합니다.

setx AZURE_COMMUNICATION_CONNECTION_STRING "<yourConnectionString>"

환경 변수를 추가한 후에는 콘솔 창을 포함하여 실행 중인 프로그램 중에서 환경 변수를 읽어야 하는 프로그램을 다시 시작해야 할 수도 있습니다. 예를 들어 편집기로 Visual Studio를 사용하는 경우 Visual Studio를 다시 시작한 후 예제를 실행합니다.

환경 변수에 액세스 토큰 저장

환경 변수를 구성하려면 콘솔 창을 열고 아래 탭에서 운영 체제를 선택합니다. <yourAccessToken>을 실제 액세스 토큰으로 바꿉니다.

콘솔 창을 열고 다음 명령을 입력합니다.

setx AZURE_COMMUNICATION_ACCESS_TOKEN "<yourAccessToken>"

환경 변수를 추가한 후에는 콘솔 창을 포함하여 실행 중인 프로그램 중에서 환경 변수를 읽어야 하는 프로그램을 다시 시작해야 할 수도 있습니다. 예를 들어 편집기로 Visual Studio를 사용하는 경우 Visual Studio를 다시 시작한 후 예제를 실행합니다.

작업

ID 만들기

액세스 토큰을 만들려면 ID가 필요합니다. Azure Communication Services는 이를 위해 간단한 ID 디렉터리를 유지 관리합니다. user create 명령을 사용하여 고유한 Id가 있는 디렉터리에 새 항목을 만듭니다. 이 ID는 나중에 액세스 토큰을 발급하는 데 필요합니다.

az communication identity user create --connection-string "<yourConnectionString>"
  • <yourConnectionString>을 연결 문자열로 바꿉니다.

ID를 만들고 동일한 요청 내에서 액세스 토큰을 발급합니다.

다음 명령을 실행하여 Communication Services ID를 만들고 동시에 액세스 토큰을 발급할 수 있습니다. scopes 매개 변수는 액세스 토큰 권한 및 역할 집합을 정의합니다. 자세한 내용은 Azure Communication Services에서 인증 받기에서 지원되는 작업 목록을 참조하세요.

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

코드에서 다음을 대체합니다.

  • <yourConnectionString>을 연결 문자열로 바꿉니다.

액세스 토큰 발급

다음 명령을 실행하여 Communication Services ID에 대한 액세스 토큰을 실행합니다. scopes 매개 변수는 액세스 토큰 권한 및 역할 집합을 정의합니다. 자세한 내용은 Azure Communication Services에서 인증 받기에서 지원되는 작업 목록을 참조하세요.

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

코드에서 다음을 대체합니다.

  • <yourConnectionString>을 연결 문자열로 바꿉니다.
  • <userId>를 userId로 바꿉니다.

액세스 토큰은 다시 발급해야 하는 단기 자격 증명입니다. 이렇게 하지 않으면 애플리케이션의 사용자 환경이 중단될 수 있습니다. expires_on 응답 속성은 액세스 토큰의 수명을 나타냅니다.

여러 범위의 액세스 토큰 발급

다음 명령을 실행하여 Communication Services ID에 대한 여러 범위의 액세스 토큰을 발급합니다. scopes 매개 변수는 액세스 토큰 권한 및 역할 집합을 정의합니다. 자세한 내용은 ID 모델에서 지원되는 작업 목록을 참조하세요.

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

코드에서 다음을 대체합니다.

  • <yourConnectionString>을 연결 문자열로 바꿉니다.
  • <userId>를 userId로 바꿉니다.

액세스 토큰은 다시 발급해야 하는 단기 자격 증명입니다. 이렇게 하지 않으면 애플리케이션의 사용자 환경이 중단될 수 있습니다. expires_on 응답 속성은 액세스 토큰의 수명을 나타냅니다.

Teams 사용자의 Microsoft Entra 액세스 토큰을 통신 ID 액세스 토큰으로 교환합니다.

token get-for-teams-user 명령을 사용하여 Azure Communication Services SDK와 함께 사용할 수 있는 Teams 사용자에 대한 액세스 토큰을 발급합니다.

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

코드에서 다음을 대체합니다.

  • <yourConnectionString>을 연결 문자열로 바꿉니다.
  • <yourAadUser>를 Microsoft Entra 사용자 ID로 바꿉니다.
  • <yourAadApplication>를 Microsoft Entra 애플리케이션 ID로 대체합니다.
  • <yourAadToken>을 Microsoft Entra 액세스 토큰으로 대체합니다.

액세스 토큰 취소

액세스 토큰을 명시적으로 해지해야 하는 경우도 있습니다. 예를 들어 애플리케이션 사용자가 서비스에서 인증을 받는 데 사용하는 암호를 변경할 때 토큰을 명시적으로 해지해야 할 수 있습니다. token revoke 명령은 ID에 발급된 모든 활성 액세스 토큰을 무효화합니다.

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

코드에서 다음을 대체합니다.

  • <yourConnectionString>을 연결 문자열로 바꿉니다.
  • <userId>를 userId로 바꿉니다.

ID 삭제

ID를 삭제하면 모든 활성 액세스 토큰이 해지되고 ID에 대한 액세스 토큰의 추가 발급이 방지됩니다. 또한 ID와 연결된 모든 지속형 콘텐츠도 제거됩니다.

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

코드에서 다음을 대체합니다.

  • <yourConnectionString>을 연결 문자열로 바꿉니다.
  • <userId>를 userId로 바꿉니다.

필수 조건

최종 코드

GitHub에서 이 빠른 시작에 대한 최종 코드를 찾습니다.

환경 설정

새 C# 애플리케이션 만들기

명령 프롬프트 창(예: cmd, PowerShell 또는 Bash)에서 dotnet new 명령을 실행하여 AccessTokensQuickstart이라는 새 콘솔 앱을 만듭니다. 이 명령은 program.cs라는 단일 원본 파일을 사용하여 간단한 "Hello World" C# 프로젝트를 만듭니다.

dotnet new console -o AccessTokensQuickstart

디렉터리를 새로 만든 앱 폴더로 변경하고 dotnet build 명령을 사용하여 애플리케이션을 컴파일합니다.

cd AccessTokensQuickstart
dotnet build

간단한 "Hello World" 출력이 표시됩니다. 이 경우 설정이 올바르게 작동하며 Azure Communication Services 관련 코드 작성을 시작할 수 있습니다.

패키지 설치

애플리케이션 디렉터리에 있는 동안 dotnet add package 명령을 사용하여 .NET 패키지용 Azure Communication Services ID 라이브러리를 설치합니다.

dotnet add package Azure.Communication.Identity

앱 프레임워크 설정

프로젝트 디렉터리에서 다음을 수행합니다.

  1. 텍스트 편집기에서 Program.cs 파일을 엽니다.
  2. Azure.Communication.Identity 네임스페이스를 포함하는 using 지시문 추가합니다.
  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이라는 환경 변수에서 리소스에 대한 연결 문자열을 검색합니다.

자세한 내용은 Communication Services 리소스 만들기 및 관리의 "연결 문자열 저장" 섹션을 참조하세요.

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

ID 만들기

액세스 토큰을 만들려면 ID가 필요합니다. Azure Communication Services는 이를 위해 간단한 ID 디렉터리를 유지 관리합니다. createUser 메서드를 사용하여 고유한 Id가 있는 디렉터리에 새 항목을 만듭니다. 이 ID는 나중에 액세스 토큰을 발급하는 데 필요합니다.

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

수신된 ID를 애플리케이션의 사용자에 매핑하여 저장합니다(예: 애플리케이션 서버 데이터베이스에 저장).

액세스 토큰 발급

Communication Services ID가 있으면 GetToken 메서드를 사용하여 액세스 토큰을 발급합니다. scopes 매개 변수는 액세스 토큰 권한 및 역할 집합을 정의합니다. 자세한 내용은 ID 모델에서 지원되는 작업 목록을 참조하세요. Azure Communication Service ID의 문자열 표현에 따라 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);

ID를 만들고 동일한 요청 내에서 토큰 발급

CreateUserAndTokenAsync 메서드를 사용하여 Communication Services ID를 만들고 동시에 액세스 토큰을 발급할 수 있습니다. scopes 매개 변수는 액세스 토큰 권한 및 역할 집합을 정의합니다. 자세한 내용은 Azure Communication Services에서 인증 받기에서 지원되는 작업 목록을 참조하세요.

// 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를 만들어야 하는 경우 다음과 같이 저장된 IdCommunicationUserIdentifier 생성자에 전달하면 됩니다.

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

액세스 토큰 취소

액세스 토큰을 명시적으로 해지해야 하는 경우도 있습니다. 예를 들어 애플리케이션 사용자가 서비스에서 인증을 받는 데 사용하는 암호를 변경할 때 토큰을 명시적으로 해지해야 할 수 있습니다. RevokeTokensAsync 메서드는 ID에 발급된 모든 활성 액세스 토큰을 무효화합니다.

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

ID 삭제

ID를 삭제하면 모든 활성 액세스 토큰이 해지되고 ID에 대한 액세스 토큰의 추가 발급이 방지됩니다. 또한 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 애플리케이션 만들기

터미널 또는 명령 프롬프트 창에서 앱에 대한 새 디렉터리를 만든 다음, 엽니다.

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

npm init -y를 실행하여 기본 설정으로 package.json 파일을 만듭니다.

npm init -y

패키지 설치

npm install 명령을 사용하여 JavaScript용 Azure Communication Services ID 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이라는 환경 변수에서 리소스에 대한 연결 문자열을 검색합니다.

자세한 내용은 Communication Services 리소스 만들기 및 관리의 "연결 문자열 저장" 섹션을 참조하세요.

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

ID 만들기

액세스 토큰을 만들려면 ID가 필요합니다. Azure Communication Services는 이를 위해 간단한 ID 디렉터리를 유지 관리합니다. createUser 메서드를 사용하여 고유한 Id가 있는 디렉터리에 새 항목을 만듭니다. 이 ID는 나중에 액세스 토큰을 발급하는 데 필요합니다.

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

수신된 ID를 애플리케이션의 사용자에 매핑하여 저장합니다(예: 애플리케이션 서버 데이터베이스에 저장).

액세스 토큰 발급

getToken 메서드를 사용하여 Communication Services ID에 대한 액세스 토큰을 발급합니다. scopes 매개 변수는 액세스 토큰 권한 및 역할 집합을 정의합니다. 자세한 내용은 ID 모델에서 지원되는 작업 목록을 참조하세요. Azure Communication Service ID의 문자열 표현에 따라 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);

한 번의 메서드 호출로 ID 생성 및 토큰 발급

createUserAndToken 메서드를 사용하여 Communication Services ID를 만들고 동시에 액세스 토큰을 발급할 수 있습니다. 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);

액세스 토큰 새로 고침

토큰이 만료되면 주기적으로 새로 고쳐야 합니다. 토큰을 발급하는 데 사용된 것과 동일한 ID를 사용하여 다시 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 메서드는 ID에 발급된 모든 활성 액세스 토큰을 무효화합니다.

await identityClient.revokeTokens(identityResponse);

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

ID 삭제

ID를 삭제하면 모든 활성 액세스 토큰이 해지되고 ID에 대한 액세스 토큰의 추가 발급이 방지됩니다. 또한 ID와 연결된 모든 지속형 콘텐츠도 제거됩니다.

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 Communication Services ID SDK를 설치합니다.

pip install azure-communication-identity

클라이언트 인증

연결 문자열로 CommunicationIdentityClient를 인스턴스화합니다. try 블록에 추가하는 다음 코드는 COMMUNICATION_SERVICES_CONNECTION_STRING이라는 환경 변수에서 리소스에 대한 연결 문자열을 검색합니다.

자세한 내용은 Communication Services 리소스 만들기 및 관리의 "연결 문자열 저장" 섹션을 참조하세요.

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

ID 만들기

액세스 토큰을 만들려면 ID가 필요합니다. Azure Communication Services는 이를 위해 간단한 ID 디렉터리를 유지 관리합니다. create_user 메서드를 사용하여 고유한 Id가 있는 디렉터리에 새 항목을 만듭니다. 이 ID는 나중에 액세스 토큰을 발급하는 데 필요합니다.

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

수신된 ID를 애플리케이션의 사용자에 매핑하여 저장합니다(예: 애플리케이션 서버 데이터베이스에 저장).

액세스 토큰 발급

get_token 메서드를 사용하여 Communication Services ID에 대한 액세스 토큰을 발급합니다. scopes 매개 변수는 액세스 토큰 권한 및 역할 집합을 정의합니다. 자세한 내용은 ID 모델에서 지원되는 작업 목록을 참조하세요. Azure Communication Service ID의 문자열 표현에 따라 매개 변수 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)

ID를 만들고 동일한 요청 내에서 액세스 토큰을 발급합니다.

create_user_and_token 메서드를 사용하여 Communication Services ID를 만들고 동시에 액세스 토큰을 발급할 수 있습니다. scopes 매개 변수는 액세스 토큰 권한 및 역할 집합을 정의합니다. 자세한 내용은 Azure Communication Services에서 인증 받기에서 지원되는 작업 목록을 참조하세요.

# 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 개체를 사용하여 기존 ID를 전달하여 토큰을 다시 발급합니다.

# 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 메서드는 ID에 발급된 모든 활성 액세스 토큰을 무효화합니다.

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

ID 삭제

ID를 삭제하면 모든 활성 액세스 토큰이 해지되고 ID에 대한 액세스 토큰의 추가 발급이 방지됩니다. 또한 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입니다. 이 파일은 프로젝트 구성 매개 변수에 사용됩니다.

Communication Services 패키지 설치

텍스트 편집기에서 pom.xml 파일을 엽니다. 종속성 그룹에 다음 종속성 요소를 추가합니다.

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

이 코드는 나중에 사용할 Communication Services ID SDK를 설치하도록 Maven에 지시합니다.

앱 프레임워크 설정

프로젝트 디렉터리에서 다음을 수행합니다.

  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를 인스턴스화합니다. 자세한 내용은 Communication Services 리소스 만들기 및 관리의 "연결 문자열 저장" 섹션을 참조하세요.

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

ID 만들기

액세스 토큰을 만들려면 ID가 필요합니다. Azure Communication Services는 이를 위해 간단한 ID 디렉터리를 유지 관리합니다. createUser 메서드를 사용하여 고유한 Id가 있는 디렉터리에 새 항목을 만듭니다.

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

생성된 ID는 나중에 액세스 토큰을 발급하는 데 필요합니다. 수신된 ID를 애플리케이션의 사용자에 매핑하여 저장합니다(예: 애플리케이션 서버 데이터베이스에 저장).

액세스 토큰 발급

getToken 메서드를 사용하여 Communication Services ID에 대한 액세스 토큰을 발급합니다. scopes 매개 변수는 액세스 토큰 권한 및 역할 집합을 정의합니다. 자세한 내용은 ID 모델에서 지원되는 작업 목록을 참조하세요.

다음 코드에서는 이전 단계에서 만든 사용자 변수를 사용하여 토큰을 가져옵니다.

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

한 번의 요청으로 ID 생성 및 토큰 발급

또는 '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());

ID 삭제

ID를 삭제하면 모든 활성 액세스 토큰이 해지되고 ID에 대한 액세스 토큰의 추가 발급이 방지됩니다. 또한 ID와 연결된 모든 지속형 콘텐츠도 제거됩니다.

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 Portal에서 Communication Services 리소스 내의 ID 및 사용자 액세스 토큰 블레이드로 이동합니다.

액세스 토큰의 범위를 선택합니다. 없음, 1개 또는 여러 개를 선택할 수 있습니다. 생성을 클릭합니다.

ID 및 액세스 토큰의 범위를 선택합니다.

ID와 해당 사용자 액세스 토큰이 생성되는 것을 확인할 수 있습니다. 이 문자열을 복사하여 샘플 앱과 기타 테스트 시나리오에서 사용할 수 있습니다.

ID 및 액세스 토큰이 생성되고 만료 날짜가 표시됩니다.

필수 조건

사용자 만들기

Azure Communication Services ID 커넥터를 사용하여 워크플로에 새 단계를 추가하고 편집 모드에서 Power Automate 흐름을 연 상태에서 Power Automate에서 다음 단계를 따릅니다.

  1. 새 작업을 추가하려는 디자이너 단계에서 새 단계를 선택합니다. 또는 새 작업을 단계 사이에 추가하려면 포인터를 해당 단계 사이의 화살표 위로 이동하고, 더하기 기호(+)를 선택한 다음, [작업 추가]를 선택합니다.

  2. 작업 선택 검색 상자에 Communication Services ID를 입력합니다. 작업 목록에서 사용자 만들기를 선택합니다.

    Azure Communication Services ID 커넥터 사용자 만들기 작업을 보여 주는 스크린샷

  3. 연결 문자열을 제공합니다. Azure Communication Service 리소스 내의 Microsoft Azure 왼쪽 메뉴 > 연결 문자열의 키 옵션에서 찾을 수 있습니다.

    Azure Communication Services 리소스 내의 키 페이지를 보여 주는 스크린샷

  4. 연결 이름 제공

  5. 만들기를 클릭합니다.

    이 작업은 Communication Services 사용자 ID인 사용자 ID를 출력합니다. 또한 "고급 옵션 표시"를 클릭하고 토큰 범위를 선택하면 지정된 범위의 액세스 토큰과 만료 시간도 출력됩니다.

    Azure Communication Services 커넥터 사용자 만들기 작업을 보여 주는 스크린샷

    Azure Communication Services 커넥터 사용자 만들기 작업 고급 옵션을 보여 주는 스크린샷

사용자 액세스 토큰 발급

Communication Services ID가 있으면 사용자 액세스 토큰 발급 작업을 사용하여 액세스 토큰을 발급할 수 있습니다. 다음 단계는 방법을 보여 줍니다.

  1. 새 작업을 추가하고 검색 상자에 Communication Services ID를 입력합니다. 작업 목록에서 사용자 액세스 토큰 발급을 선택합니다.

    Azure Communication Services ID 커넥터 발급 액세스 토큰 작업을 보여 주는 스크린샷

  2. 그런 다음 이전 사용자 만들기 단계에서 출력된 사용자 ID를 사용할 수 있습니다.

  3. 토큰 범위 지정: VoIP 또는 채팅. 토큰 및 인증에 대해 자세히 알아보기

    토큰 범위를 지정하는 Azure Communication Services ID 커넥터 발급 액세스 토큰 작업을 보여 주는 스크린샷

이렇게 하면 지정된 범위의 액세스 토큰과 만료 시간이 출력됩니다.

사용자 액세스 토큰 취소

Communication Services ID가 있으면 사용자 액세스 토큰 발급 작업을 사용하여 액세스 토큰을 해지할 수 있습니다. 다음 단계는 방법을 보여 줍니다.

  1. 새 작업을 추가하고 검색 상자에 Communication Services ID를 입력합니다. 작업 목록에서 사용자 액세스 토큰 해지를 선택합니다.

    Azure Communication Services ID 커넥터 액세스 토큰 해지 작업을 보여 주는 스크린샷

  2. 사용자 ID 지정

    Azure Communication Services ID 커넥터 액세스 토큰 해지 작업 입력을 보여 주는 스크린샷

이렇게 하면 지정된 사용자에 대한 모든 사용자 액세스 토큰이 해지되며 이 작업에 대한 출력이 없습니다.

사용자 삭제

Communication Services ID가 있으면 사용자 액세스 토큰 발급 작업을 사용하여 액세스 토큰을 삭제할 수 있습니다. 다음 단계는 방법을 보여 줍니다.

  1. 새 작업을 추가하고 검색 상자에 Communication Services ID를 입력합니다. 작업 목록에서 사용자 삭제를 선택합니다.

    Azure Communication Services ID 커넥터 사용자 삭제 작업을 보여 주는 스크린샷

  2. 사용자 ID 지정

    Azure Communication Services ID 커넥터 사용자 삭제 작업 입력을 보여 주는 스크린샷

    이렇게 하면 사용자가 제거되고 지정된 사용자에 대한 모든 사용자 액세스 토큰이 해지됩니다. 이 작업에 대한 출력은 없습니다.

논리 앱 테스트

워크플로를 수동으로 시작하려면 디자이너 도구 모음에서 실행을 선택합니다. 워크플로는 사용자를 만들고 해당 사용자에 대한 액세스 토큰을 발급한 다음, 이를 제거하고 사용자를 삭제해야 합니다. 자세한 내용은 워크플로를 실행하는 방법을 검토하세요. 워크플로가 성공적으로 실행된 후 이러한 작업의 출력을 확인할 수 있습니다.

모니터링 및 메트릭에 ID 사용

사용자 ID는 Azure Monitor를 통해 수집되는 로그 및 메트릭의 기본 키 역할을 합니다. 예를 들어, 사용자의 모든 호출을 보려면 특정 Azure Communication Services ID를 단일 사용자에게 매핑하는 방식으로 인증을 설정할 수 있습니다.

인증 개념에 대해 자세히 알아보고, 사용할 수 있는 로그 분석메트릭을 통해 진단을 요청하세요.

리소스 정리

Communication Services 구독을 정리하고 제거하려면 리소스 또는 리소스 그룹을 삭제합니다. 리소스 그룹을 삭제하면 연결된 다른 리소스도 삭제됩니다. 자세한 내용은 Communication Services 리소스 만들기 및 관리의 "리소스 정리" 섹션을 참조하세요.

논리 앱 워크플로 및 관련 리소스를 정리하려면 Azure Logic Apps 리소스를 정리하는 방법을 검토하세요.

다음 단계

이 빠른 시작에서는 다음과 같은 방법을 배웠습니다.

  • 액세스 토큰 발급
  • ID 관리

다음을 수행할 수도 있습니다.

다음 단계

이 빠른 시작에서 Azure Communication Services ID 커넥터를 사용하여 사용자를 만들고, 사용자를 삭제하고, 사용자에게 액세스 토큰을 발급하고, 사용자 액세스 토큰을 제거하는 방법을 알아보았습니다. 자세히 알아보려면 Azure Communication Services Identity Connector 설명서를 확인합니다.

다른 커넥터에서 토큰을 사용하는 방법을 보려면 Azure Communication Services를 사용하여 Power Automate에서 채팅 메시지를 보내는 방법을 확인합니다.

Azure Communication Services 이메일 커넥터를 사용하여 이메일을 보내는 방법에 대해 자세히 알아보려면 Azure Communication Services를 사용하여 Power Automate에서 이메일 메시지 보내기를 확인합니다.