다른 Azure 리소스에 Azure 호스팅 앱을 인증하는 권장 방법은 관리 ID를 사용하는 것입니다. 이 방법은 Azure App Service, Azure Container Apps 및 Azure Virtual Machines에서 호스트되는 앱을 포함하여 대부분의 Azure 서비스에 대해 지원됩니다.
인증 개요 페이지에서 다양한 인증 기술 및 접근 방식에 대해 자세히 알아봅니다. 앞의 섹션에서는 다음을 알아봅니다.
- 필수 관리 ID 개념
- 앱에 대한 사용자 할당 관리 ID를 만드는 방법
- 사용자 할당 관리 ID에 역할을 할당하는 방법
- 앱 코드에서 사용자 할당 관리 ID를 사용하여 인증하는 방법
필수 관리 ID 개념
관리 ID를 사용하면 앱이 비밀 키 또는 다른 애플리케이션 비밀을 사용하지 않고도 다른 Azure 리소스에 안전하게 연결할 수 있습니다. 내부적으로 Azure는 ID와 연결할 수 있는 리소스를 추적합니다. Azure는 이 정보를 사용하여 앱이 다른 Azure 리소스에 연결할 수 있도록 앱에 대한 Microsoft Entra 토큰을 자동으로 가져옵니다.
호스트된 앱을 구성할 때 고려해야 할 관리 ID에는 두 가지 유형이 있습니다.
-
시스템 할당 관리 ID는 Azure 리소스에서 직접 사용하도록 설정되며 수명 주기에 연결됩니다. 리소스가 삭제되면 Azure에서 자동으로 ID를 삭제합니다. 시스템 할당 ID는 관리 ID를 사용하는 최소한의 접근 방식을 제공합니다.
-
사용자 할당 관리 ID는 독립 실행형 Azure 리소스로 만들어지고 더 큰 유연성과 기능을 제공합니다. 동일한 ID 및 권한을 공유해야 하는 여러 Azure 리소스와 관련된 솔루션에 이상적입니다. 예를 들어 여러 가상 머신이 동일한 Azure 리소스 집합에 액세스해야 하는 경우 사용자 할당 관리 ID는 재사용 가능성과 최적화된 관리를 제공합니다.
다음 섹션에서는 Azure 호스팅 앱에 대해 사용자 할당 관리 ID를 사용하도록 설정하고 사용하는 단계를 설명합니다. 시스템 할당 관리 ID를 사용해야 하는 경우 시스템 할당 관리 ID 문서를 참조하세요.
사용자 할당 관리 ID 만들기
사용자가 할당한 관리 ID는 Azure Portal 또는 Azure CLI를 사용하여 Azure 구독에서 독립 실행형 리소스로 만들어집니다. Azure CLI 명령은 Azure Cloud Shell 또는 Azure CLI가 설치된 워크스테이션에서 실행할 수 있습니다.
Azure Portal의 기본 검색 창에 관리 ID 를 입력하고 서비스 섹션에서 일치하는 결과를 선택합니다.
관리 ID 페이지에서 + 만들기를 선택합니다.
사용자 할당 관리 ID 만들기 페이지에서 사용자가 할당한 관리 ID에 대한 구독, 리소스 그룹 및 지역을 선택한 다음 이름을 입력합니다.
검토 + 만들기를 선택하여 입력을 검토하고 유효성을 검사합니다.
만들기를 선택하여 사용자 할당 관리 ID를 만듭니다.
ID를 만든 후 리소스로 이동을 선택합니다.
새 ID의 개요 페이지에서 나중에 애플리케이션 코드를 구성할 때 사용할 클라이언트 ID 값을 복사합니다.
Azure CLI 명령을 az identity create 사용하여 관리 ID를 만듭니다.
az identity create \
--resource-group <resource-group-name> \
--name <identity-name> \
--query 'clientId' \
--output json
명령 출력은 생성된 사용자 할당 관리 ID의 클라이언트 ID를 출력합니다. 클라이언트 ID는 ID를 사용하는 애플리케이션 코드를 구성하는 데 사용됩니다.
언제든지 다음 명령을 사용하여 az identity show 관리 ID 속성을 다시 볼 수 있습니다.
az identity show \
--resource-group <your-resource-group> \
--name <your-managed-identity-name> \
--output json
앱에 관리 ID 할당
사용자 할당 관리 ID는 하나 이상의 Azure 리소스와 연결할 수 있습니다. 해당 ID를 사용하는 모든 리소스는 ID의 역할을 통해 적용된 권한을 얻습니다.
Azure Portal에서 Azure App Service 또는 Azure Container App 인스턴스와 같은 앱 코드를 호스트하는 리소스로 이동합니다.
리소스의 개요 페이지에서 설정을 확장하고 탐색에서 ID 를 선택합니다.
ID 페이지에서 사용자 할당 탭으로 전환합니다.
+ 추가를 선택하여 사용자 할당 관리 ID 추가 패널을 엽니다.
사용자 할당 관리 ID 추가 패널에서 구독 드롭다운을 사용하여 ID에 대한 검색 결과를 필터링합니다.
사용자가 할당한 관리 ID 검색 상자를 사용하여 앱을 호스팅하는 Azure 리소스에 대해 사용하도록 설정한 사용자 할당 관리 ID를 찾습니다.
ID를 선택하고 패널 아래쪽에서 추가 를 선택하여 계속합니다.
Azure CLI는 다양한 유형의 호스팅 서비스에 사용자 할당 관리 ID를 할당하는 다양한 명령을 제공합니다.
Azure CLI를 사용하여 Azure App Service 웹앱과 같은 리소스에 사용자 할당 관리 ID를 할당하려면 ID의 리소스 ID가 필요합니다. 명령을 az identity show 사용하여 리소스 ID를 검색합니다.
az identity show \
--resource-group <your-resource-group> \
--name <your-managed-identity-name> \
--output json \
--query id
리소스 ID가 있으면 Azure CLI 명령 명령을 az <resourceType> identity assign 사용하여 사용자 할당 관리 ID를 다음과 같은 다른 리소스와 연결합니다.
Azure App Service의 경우 Azure CLI 명령을 az webapp identity assign사용합니다.
az webapp identity assign \
--resource-group <resource-group-name> \
--name <webapp-name> \
--identities <user-assigned-identity-resource-id>
Azure Container Apps의 경우 Azure CLI 명령을 az containerapp identity assign사용합니다.
az containerapp identity assign \
--resource-group <resource-group-name> \
--name <containerapp-name> \
--identities <user-assigned-identity-resource-id>
Azure Virtual Machines의 경우 Azure CLI 명령을 az vm identity assign사용합니다.
az vm identity assign \
--resource-group <resource-group-name> \
--name <vm-name> \
--identities <user-assigned-identity-resource-id>
관리 ID에 역할 할당
다음으로 앱에 필요한 역할을 결정하고 관리 ID에 해당 역할을 할당합니다. 다음 범위에서 관리 ID에 역할을 할당할 수 있습니다.
-
리소스: 할당된 역할은 해당 특정 리소스에만 적용됩니다.
-
리소스 그룹: 할당된 역할은 리소스 그룹에 포함된 모든 리소스에 적용됩니다.
-
구독: 할당된 역할은 구독에 포함된 모든 리소스에 적용됩니다.
다음 예제에서는 많은 앱이 단일 리소스 그룹을 사용하여 관련된 모든 Azure 리소스를 관리하므로 리소스 그룹 범위에서 역할을 할당하는 방법을 보여 줍니다.
사용자가 할당한 관리 ID가 있는 앱이 포함된 리소스 그룹의 개요 페이지로 이동합니다.
왼쪽 탐색 영역에서 액세스 제어(IAM) 를 선택합니다.
액세스 제어(IAM) 페이지에서 위쪽 메뉴에서 + 추가를 선택한 다음 역할 할당 추가를 선택하여 역할 할당 추가 페이지로 이동합니다.
역할 할당 추가 페이지에는 ID에 역할을 할당하는 탭이 있는 다단계 워크플로가 표시됩니다. 초기 역할 탭에서 맨 위에 있는 검색 상자를 사용하여 ID에 할당할 역할을 찾습니다.
결과에서 역할을 선택한 다음 [다음 ]을 선택하여 [멤버 ] 탭으로 이동합니다.
액세스 할당 옵션에 대해 관리 ID를 선택합니다.
구성원 옵션의 경우 + 멤버 선택을 선택하여관리 ID 선택 패널을 엽니다.
관리 ID 선택 패널에서 구독 및 관리 ID 드롭다운을 사용하여 ID에 대한 검색 결과를 필터링합니다.
검색 선택 상자를 사용하여 앱을 호스팅하는 Azure 리소스에 대해 사용하도록 설정한 사용자 할당 관리 ID를 찾습니다.
ID를 선택하고 패널 아래쪽에서 [선택] 을 선택하여 계속합니다.
페이지 아래쪽에서 검토 + 할당 을 선택합니다.
최종 검토 + 할당 탭에서 검토 + 할당 을 선택하여 워크플로를 완료합니다.
Azure CLI를 사용하여 사용자 할당 관리 ID에 역할을 할당하려면 ID의 보안 주체 ID가 필요합니다. 명령을 az identity show 사용하여 보안 주체 ID를 검색합니다.
az identity show \
--resource-group <your-resource-group> \
--name <your-managed-identity-name> \
--output json \
--query principalId
az role definition list 명령을 사용하여 관리 ID를 할당할 수 있는 역할을 탐색합니다.
az role definition list \
--query "sort_by([].{roleName:roleName, description:description}, &roleName)" \
--output table
az role assignment create 명령을 사용하여 관리 ID에 역할을 할당합니다.
az role assignment create \
--assignee <your-principal-id> \
--role <role-name> \
--scope <scope>
예를 들어 99999999-9999-9999-9999-999999999999 리소스 그룹의 모든 스토리지 계정에 대한 Azure Storage Blob 컨테이너 및 데이터에 대한 읽기, 쓰기 및 삭제 액세스 권한이 있는 관리 ID를 허용하려면 다음 명령을 사용하여 애플리케이션 서비스 주체를 Storage Blob 데이터 기여자 역할에 할당합니다.
az role assignment create \
--assignee 99999999-9999-9999-9999-999999999999 \
--role "Storage Blob Data Contributor" \
--scope "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/msdocs-sdk-auth-example"
Azure CLI를 사용하여 리소스 또는 구독 수준에서 권한을 할당하는 방법에 대한 자세한 내용은 Azure CLI를 사용하여 Azure 역할 할당 문서를 참조하세요.
앱에서 Azure 서비스에 인증
Azure ID 라이브러리는 다양한 시나리오 및 Microsoft Entra 인증 흐름을 지원하는 데 적합한 구현 인 다양한 TokenCredential을 제공합니다. 로컬로 실행할 때 관리 ID를 사용할 수 없으므로 다음 단계에서는 어떤 시나리오에서 사용할 자격 증명을 보여 줍니다.
코드 구현
JavaScript 프로젝트에서 @azure/ID 패키지를 추가합니다. 선택한 터미널에서 애플리케이션 프로젝트 디렉터리로 이동하고 다음 명령을 실행합니다.
npm install @azure/identity
Azure 서비스는 다양한 Azure SDK 클라이언트 라이브러리의 특수 클라이언트 클래스를 사용하여 액세스합니다. 다음 index.js단계를 완료하여 토큰 기반 인증을 구성합니다.
-
@azure/identity 패키지를 가져옵니다.
- 클라이언트에 적절한
TokenCredential 인스턴스를 전달합니다.
- 앱이 로컬로 실행 중일 때 사용합니다
DefaultAzureCredential .
- 앱이 Azure에서 실행 중일 때 사용하고
ManagedIdentityCredential 클라이언트 ID, 리소스 ID 또는 개체 ID를 구성합니다.
클라이언트 ID는 해당 ID를 사용하여 인증해야 하는 애플리케이션 또는 서비스를 구성할 때 관리 ID를 식별하는 데 사용됩니다.
다음 명령을 사용하여 사용자 할당 관리 ID에 할당된 클라이언트 ID를 검색합니다.
az identity show \
--resource-group <resource-group-name> \
--name <identity-name> \
--query 'clientId'
클라이언트 ID를 사용하여 구성 ManagedIdentityCredential :
import { BlobServiceClient } from '@azure/storage-blob';
import { ManagedIdentityCredential, DefaultAzureCredential } from '@azure/identity';
console.log(process.env);
function createBlobServiceClient() {
const accountName = process.env.AZURE_STORAGE_ACCOUNT_NAME;
if (!accountName) throw Error('Azure Storage accountName not found');
const url = `https://${accountName}.blob.core.windows.net`;
if (process.env.NODE_ENV === "production") {
const clientId = process.env.AZURE_CLIENT_ID;
if (!clientId) throw Error('AZURE_CLIENT_ID not found for Managed Identity');
return new BlobServiceClient(url, new ManagedIdentityCredential(clientId));
} else {
return new BlobServiceClient(url, new DefaultAzureCredential());
}
}
async function main() {
try {
const blobServiceClient = createBlobServiceClient();
const containerClient = blobServiceClient.getContainerClient(process.env.AZURE_STORAGE_CONTAINER_NAME);
// do something with client
const properties = await containerClient.getProperties();
console.log(properties);
} catch (err) {
console.error("Error retrieving container properties:", err.message);
throw err;
}
}
main().catch((err) => {
console.error("Error running sample:", err.message);
process.exit(1);
});
리소스 ID는 다음 구조를 사용하여 Azure 구독 내에서 관리 ID 리소스를 고유하게 식별합니다.
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}
규칙에 따라 리소스 ID를 빌드할 수 있으므로 사용자 환경에서 많은 수의 사용자 할당 관리 ID로 작업할 때 더 편리합니다.
다음 명령을 사용하여 사용자 할당 관리 ID의 리소스 ID를 검색합니다.
az identity show \
--resource-group <resource-group-name> \
--name <identity-name> \
--query 'id'
리소스 ID를 사용하여 구성 ManagedIdentityCredential 합니다.
import { BlobServiceClient } from '@azure/storage-blob';
import { ManagedIdentityCredential, DefaultAzureCredential } from '@azure/identity';
function createBlobServiceClient() {
const accountName = process.env.AZURE_STORAGE_ACCOUNT_NAME;
if (!accountName) throw Error('Azure Storage accountName not found');
const url = `https://${accountName}.blob.core.windows.net`;
if (process.env.NODE_ENV === "production") {
const resourceId = process.env.AZURE_RESOURCE_ID;
if (!resourceId) throw Error('AZURE_RESOURCE_ID not found for Managed Identity');
return new BlobServiceClient(url, new ManagedIdentityCredential(resourceId));
} else {
return new BlobServiceClient(url, new DefaultAzureCredential());
}
}
async function main() {
try {
const blobServiceClient = createBlobServiceClient();
const containerClient = blobServiceClient.getContainerClient(process.env.AZURE_STORAGE_CONTAINER_NAME);
// do something with client
const properties = await containerClient.getProperties();
console.log(properties);
} catch (err) {
console.error("Error retrieving container properties:", err.message);
throw err;
}
}
main().catch((err) => {
console.error("Error running sample:", err.message);
process.exit(1);
});
보안 주체 ID는 개체 ID의 또 다른 이름입니다.
다음 명령을 사용하여 사용자 할당 관리 ID의 개체 ID를 검색합니다.
az identity show \
--resource-group <resource-group-name> \
--name <identity-name> \
--query 'principalId'
개체 ID를 사용하여 구성 ManagedIdentityCredential 합니다.
import { BlobServiceClient } from '@azure/storage-blob';
import { ManagedIdentityCredential, DefaultAzureCredential } from '@azure/identity';
function createBlobServiceClient() {
const accountName = process.env.AZURE_STORAGE_ACCOUNT_NAME;
if (!accountName) throw Error('Azure Storage accountName not found');
const url = `https://${accountName}.blob.core.windows.net`;
if (process.env.NODE_ENV === "production") {
const objectId = process.env.AZURE_OBJECT_ID;
if (!objectId) throw Error('AZURE_OBJECT_ID not found for Managed Identity');
return new BlobServiceClient(url, new ManagedIdentityCredential(objectId));
} else {
return new BlobServiceClient(url, new DefaultAzureCredential());
}
}
async function main() {
try {
const blobServiceClient = createBlobServiceClient();
const containerClient = blobServiceClient.getContainerClient(process.env.AZURE_STORAGE_CONTAINER_NAME);
// do something with client
const properties = await containerClient.getProperties();
console.log(properties);
} catch (err) {
console.error("Error retrieving container properties:", err.message);
throw err;
}
}
main().catch((err) => {
console.error("Error running sample:", err.message);
process.exit(1);
});
코드 구현
TypeScript 프로젝트에서 @azure/ID 패키지를 추가합니다. 선택한 터미널에서 애플리케이션 프로젝트 디렉터리로 이동하고 다음 명령을 실행합니다.
npm install typescript @azure/identity @types/node
Azure 서비스는 다양한 Azure SDK 클라이언트 라이브러리의 특수 클라이언트 클래스를 사용하여 액세스합니다. 다음 index.js단계를 완료하여 토큰 기반 인증을 구성합니다.
-
@azure/identity 패키지를 가져옵니다.
- 클라이언트에 적절한
TokenCredential 인스턴스를 전달합니다.
- 앱이 로컬로 실행 중일 때 사용
DefaultAzureCredential
- 앱이 Azure에서 실행 중일 때 사용하고
ManagedIdentityCredential 클라이언트 ID, 리소스 ID 또는 개체 ID를 구성합니다.
클라이언트 ID는 해당 ID를 사용하여 인증해야 하는 애플리케이션 또는 서비스를 구성할 때 관리 ID를 식별하는 데 사용됩니다.
다음 명령을 사용하여 사용자 할당 관리 ID에 할당된 클라이언트 ID를 검색합니다.
az identity show \
--resource-group <resource-group-name> \
--name <identity-name> \
--query 'clientId'
클라이언트 ID를 사용하여 구성 ManagedIdentityCredential :
import { BlobServiceClient } from '@azure/storage-blob';
import { ManagedIdentityCredential, DefaultAzureCredential } from '@azure/identity';
function createBlobServiceClient(): BlobServiceClient {
const accountName = process.env.AZURE_STORAGE_ACCOUNT_NAME;
if (!accountName) throw Error('Azure Storage accountName not found');
const url = `https://${accountName}.blob.core.windows.net`;
if (process.env.NODE_ENV === "production") {
const clientId = process.env.AZURE_CLIENT_ID;
if (!clientId) throw Error('AZURE_CLIENT_ID not found for Managed Identity');
return new BlobServiceClient(url, new ManagedIdentityCredential(clientId));
} else {
return new BlobServiceClient(url, new DefaultAzureCredential());
}
}
async function main(): Promise<void> {
try {
const blobServiceClient = createBlobServiceClient();
const containerClient = blobServiceClient.getContainerClient(process.env.AZURE_STORAGE_CONTAINER_NAME!);
const properties = await containerClient.getProperties();
console.log(properties);
} catch (err: any) {
console.error("Error retrieving container properties:", err.message);
throw err;
}
}
main().catch((err: Error) => {
console.error("Error running sample:", err.message);
process.exit(1);
});
리소스 ID는 다음 구조를 사용하여 Azure 구독 내에서 관리 ID 리소스를 고유하게 식별합니다.
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}
규칙에 따라 리소스 ID를 빌드할 수 있으므로 사용자 환경에서 많은 수의 사용자 할당 관리 ID로 작업할 때 더 편리합니다.
다음 명령을 사용하여 사용자 할당 관리 ID의 리소스 ID를 검색합니다.
az identity show \
--resource-group <resource-group-name> \
--name <identity-name> \
--query 'id'
리소스 ID를 사용하여 구성 ManagedIdentityCredential 합니다.
import { BlobServiceClient } from '@azure/storage-blob';
import { ManagedIdentityCredential, DefaultAzureCredential } from '@azure/identity';
function createBlobServiceClient(): BlobServiceClient {
const accountName = process.env.AZURE_STORAGE_ACCOUNT_NAME;
if (!accountName) throw Error('Azure Storage accountName not found');
const url = `https://${accountName}.blob.core.windows.net`;
if (process.env.NODE_ENV === "production") {
const resourceId = process.env.AZURE_RESOURCE_ID;
if (!resourceId) throw Error('AZURE_RESOURCE_ID not found for Managed Identity');
return new BlobServiceClient(url, new ManagedIdentityCredential(resourceId));
} else {
return new BlobServiceClient(url, new DefaultAzureCredential());
}
}
async function main(): Promise<void> {
try {
const blobServiceClient = createBlobServiceClient();
const containerClient = blobServiceClient.getContainerClient(process.env.AZURE_STORAGE_CONTAINER_NAME!);
const properties = await containerClient.getProperties();
console.log(properties);
} catch (err: any) {
console.error("Error retrieving container properties:", err.message);
throw err;
}
}
main().catch((err: Error) => {
console.error("Error running sample:", err.message);
process.exit(1);
});
보안 주체 ID는 개체 ID의 또 다른 이름입니다.
다음 명령을 사용하여 사용자 할당 관리 ID의 개체 ID를 검색합니다.
az identity show \
--resource-group <resource-group-name> \
--name <identity-name> \
--query 'principalId'
개체 ID를 사용하여 구성 ManagedIdentityCredential 합니다.
import { BlobServiceClient } from '@azure/storage-blob';
import { ManagedIdentityCredential, DefaultAzureCredential } from '@azure/identity';
function createBlobServiceClient(): BlobServiceClient {
const accountName = process.env.AZURE_STORAGE_ACCOUNT_NAME;
if (!accountName) throw Error('Azure Storage accountName not found');
const url = `https://${accountName}.blob.core.windows.net`;
if (process.env.NODE_ENV === "production") {
const objectId = process.env.AZURE_OBJECT_ID;
if (!objectId) throw Error('AZURE_OBJECT_ID not found for Managed Identity');
return new BlobServiceClient(url, new ManagedIdentityCredential(objectId));
} else {
return new BlobServiceClient(url, new DefaultAzureCredential());
}
}
async function main(): Promise<void> {
try {
const blobServiceClient = createBlobServiceClient();
const containerClient = blobServiceClient.getContainerClient(process.env.AZURE_STORAGE_CONTAINER_NAME!);
const properties = await containerClient.getProperties();
console.log(properties);
} catch (err: any) {
console.error("Error retrieving container properties:", err.message);
throw err;
}
}
main().catch((err: Error) => {
console.error("Error running sample:", err.message);
process.exit(1);
});
위의 코드는 실행 중인 환경에 따라 다르게 동작합니다.
- 로컬 개발 워크스테이션
DefaultAzureCredential 에서 애플리케이션 서비스 주체의 환경 변수 또는 Visual Studio Code와 같은 로컬로 설치된 개발자 도구에서 개발자 자격 증명 집합을 찾습니다.
- Azure
ManagedIdentityCredential 에 배포된 경우 관리 ID 구성을 검색하여 다른 서비스에 자동으로 인증합니다.