다음을 통해 공유


Azure Communication JavaScript용 공용 클라이언트 라이브러리 - 버전 2.4.0

이 패키지에는 Azure Communication Service 라이브러리에 대한 공통 코드가 포함되어 있습니다.

시작하기

필수 조건

  • Azure 구독.
  • 기존 Communication Services 리소스입니다. 리소스를 만들어야 하는 경우 Azure Portal, Azure PowerShell또는 azure CLI 사용할 수 있습니다.
  • @azure/identity 패키지를 설치합니다.

설치

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

브라우저 지원

JavaScript 번들

브라우저에서 이 클라이언트 라이브러리를 사용하려면 먼저 번들러를 사용해야 합니다. 이 작업을 수행하는 방법에 대한 자세한 내용은 번들링 설명서참조하세요.

주요 개념

CommunicationTokenCredential 및 AzureCommunicationTokenCredential

CommunicationTokenCredential 채팅 또는 통화와 같은 통신 서비스를 사용하여 사용자를 인증하는 데 사용되는 인터페이스입니다.

AzureCommunicationTokenCredential 기능은 해당 인터페이스를 구현하는 자격 증명을 생성하는 편리한 방법을 제공하며 내장된 자동 새로 고침 논리를 활용할 수 있습니다.

시나리오에 따라 다음과 같이 초기화할 수 있습니다.AzureCommunicationTokenCredential

  • 정적 토큰(예: 일회성 채팅 메시지를 보내는 데 사용되는 수명이 짧은 클라이언트에 적합) 또는
  • 통신 중에 지속적인 인증 상태를 보장하는 콜백 함수입니다(예: 긴 호출 세션의 경우).
  • Entra 사용자 토큰을 가져올 수 있는 토큰 자격 증명입니다. TokenCredential 인터페이스의 모든 구현을 제공할 수 있습니다. Communication Services를 사용하여 인증하기 위해 Entra 사용자 액세스 토큰이 필요한 시나리오에 적합합니다.

생성자 또는 토큰 새로 고침 콜백을 통해 제공된 AzureCommunicationTokenCredential 토큰은 Azure Communication Identity 라이브러리를 사용하여 가져올 수 있습니다.

예시

정적 토큰을 사용하여 자격 증명 만들기

수명이 짧은 클라이언트의 경우 만료 시 토큰을 새로 고칠 필요가 AzureCommunicationTokenCredential 없으며 정적 토큰으로 인스턴스화될 수 있습니다.

import { AzureCommunicationTokenCredential } from "@azure/communication-common";

const tokenCredential = new AzureCommunicationTokenCredential(
  "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjM2MDB9.adM-ddBZZlQ1WlN3pdPBOF5G4Wh9iZpxNP_fSvpF4cWs",
);

콜백을 사용하여 자격 증명 만들기

여기서는 사용자의 JWT 토큰 문자열을 검색하기 위해 네트워크 요청을 하는 함수가 fetchTokenFromMyServerForUser 있다고 가정합니다. 이를 자격 증명에 전달하여 자체 서버에서 Bob에 대한 토큰을 가져옵니다. 서버는 Azure Communication Identity 라이브러리를 사용하여 토큰을 발급합니다. 함수는 항상 유효한 토큰(만료 날짜가 미래로 설정됨)을 반환해야 합니다 fetchTokenFromMyServerForUser .

import { AzureCommunicationTokenCredential } from "@azure/communication-common";

function fetchTokenFromMyServerForUser(user: string): Promise<string> {
  // Your custom implementation to fetch a token for the user
  return Promise.resolve("some-unique-token-for-" + user);
}

const tokenCredential = new AzureCommunicationTokenCredential({
  tokenRefresher: async () => fetchTokenFromMyServerForUser("bob@contoso.com"),
});

사전 예방적 새로 고침을 사용하여 자격 증명 만들기

true로 설정하면 refreshProactively 토큰이 만료에 가까워 질 때 함수가 호출 tokenRefresher 됩니다.

import { AzureCommunicationTokenCredential } from "@azure/communication-common";

function fetchTokenFromMyServerForUser(user: string): Promise<string> {
  // Your custom implementation to fetch a token for the user
  return Promise.resolve("some-unique-token-for-" + user);
}

const tokenCredential = new AzureCommunicationTokenCredential({
  tokenRefresher: async () => fetchTokenFromMyServerForUser("bob@contoso.com"),
  refreshProactively: true,
});

사전 예방적 새로 고침 및 초기 토큰을 사용하여 자격 증명 만들기

전달 initialToken 은 에 대한 tokenRefresher첫 번째 호출을 건너뛰는 선택적 최적화입니다. 이를 사용하여 후속 토큰 새로 고침 주기에서 애플리케이션의 부팅을 분리할 수 있습니다.

import { AzureCommunicationTokenCredential } from "@azure/communication-common";

function fetchTokenFromMyServerForUser(user: string): Promise<string> {
  // Your custom implementation to fetch a token for the user
  return Promise.resolve("some-unique-token-for-" + user);
}

const tokenCredential = new AzureCommunicationTokenCredential({
  tokenRefresher: async () => fetchTokenFromMyServerForUser("bob@contoso.com"),
  refreshProactively: true,
  token:
    "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjM2MDB9.adM-ddBZZlQ1WlN3pdPBOF5G4Wh9iZpxNP_fSvpF4cWs",
});

Entra 사용자 토큰을 가져올 수 있는 토큰 자격 증명을 사용하여 자격 증명을 만듭니다.

Entra 사용자를 Communication Services와 함께 사용할 수 있는 시나리오의 경우 TokenCredential 인터페이스의 구현을 초기화하고 EntraCommunicationTokenCredentialOptions. 이와 함께 Azure Communication Services 리소스의 URI 및 Entra 사용자 토큰에 필요한 범위를 제공해야 합니다. 이러한 범위는 토큰에 부여된 권한을 결정합니다.

이 방법은 Teams 라이선스가 있는 Entra 사용자에게 Azure Communication Services 리소스를 통해 Teams 전화 확장성 기능을 사용할 수 있는 권한을 부여하는 데 사용해야 합니다. 이를 위해서는 범위를 제공해야 합니다 https://auth.msft.communication.azure.com/TeamsExtension.ManageCalls .

import { InteractiveBrowserCredential } from "@azure/identity";
import {
  EntraCommunicationTokenCredentialOptions,
  AzureCommunicationTokenCredential,
} from "@azure/communication-common";

const options = {
  tenantId: "<your-tenant-id>",
  clientId: "<your-client-id>",
  redirectUri: "<your-redirect-uri>",
};
const entraTokenCredential = new InteractiveBrowserCredential(options);

const entraTokenCredentialOptions: EntraCommunicationTokenCredentialOptions = {
  resourceEndpoint: "https://<your-resource>.communication.azure.com",
  tokenCredential: entraTokenCredential,
  scopes: ["https://auth.msft.communication.azure.com/TeamsExtension.ManageCalls"],
};

const credential = new AzureCommunicationTokenCredential(entraTokenCredentialOptions);

Entra 사용자가 Azure Communication Services를 활용하는 다른 시나리오는 현재 미리 보기 단계에만 있으며 프로덕션에서 사용해서는 안 됩니다. 이러한 시나리오의 범위는 형식을 따릅니다 https://communication.azure.com/clients/<ACS Scope>. 특정 범위를 제공하지 않으면 기본 범위가 로 설정됩니다 https://communication.azure.com/clients/.default.

import { InteractiveBrowserCredential } from "@azure/identity";
import {
  EntraCommunicationTokenCredentialOptions,
  AzureCommunicationTokenCredential,
} from "@azure/communication-common";

const options = {
  tenantId: "<your-tenant-id>",
  clientId: "<your-client-id>",
  redirectUri: "<your-redirect-uri>",
};
const entraTokenCredential = new InteractiveBrowserCredential(options);

const entraTokenCredentialOptions: EntraCommunicationTokenCredentialOptions = {
  resourceEndpoint: "https://<your-resource>.communication.azure.com",
  tokenCredential: entraTokenCredential,
  scopes: ["https://communication.azure.com/clients/VoIP"],
};

const credential = new AzureCommunicationTokenCredential(entraTokenCredentialOptions);

문제 해결

  • 잘못된 토큰이 지정됨: 생성자 또는 콜백에 AzureCommunicationTokenCredentialtokenRefresher 전달하는 토큰이 기본 JWT 토큰 문자열인지 확인합니다. 예를 들어 Azure Communication Identity 라이브러리 또는 REST API 를 사용하여 토큰을 가져오는 경우 응답 개체의 일부만 token 전달하고 있는지 확인합니다.

로깅 (로그 기록)

로깅을 사용하도록 설정하면 오류에 대한 유용한 정보를 파악하는 데 도움이 될 수 있습니다. HTTP 요청 및 응답 로그를 보려면 AZURE_LOG_LEVEL 환경 변수를 info설정합니다. 또는 setLogLevel@azure/logger 호출하여 런타임에 로깅을 사용하도록 설정할 수 있습니다.

import { setLogLevel } from "@azure/logger";

setLogLevel("info");

다음 단계

기여하기

이 라이브러리에 기여하려면 기여 가이드 읽어 코드를 빌드하고 테스트하는 방법에 대해 자세히 알아보세요.

  • Javascript용 Microsoft Azure SDK