Community라이팅 & 에디팅github.com

microsoft/azure-identity-dotnet

.NET용 Azure Identity 라이브러리입니다. Microsoft Entra ID를 사용하여 Azure SDK 클라이언트를 인증합니다. DefaultAzureCredential, 관리 ID, 서비스 주체 및 개발자 자격 증명에 사용합니다.

azure-identity-dotnet란 무엇인가요?

이 스킬은 .NET 개발자가 Azure Identity 라이브러리를 사용하여 Azure SDK 클라이언트를 인증하는 방법을 제공합니다. Microsoft Entra ID 기반의 다양한 인증 방식을 지원하며, 개발 환경에서 프로덕션 환경까지 원활하게 전환할 수 있도록 DefaultAzureCredential, ManagedIdentityCredential, ClientSecretCredential 등 여러 자격 증명 유형을 포함합니다. 주로 C# 프로젝트에서 Azure.Storage.Blobs, Azure.Security.KeyVault.Secrets 등과 함께 사용되며, ASP.NET Core의 DI(의존성 주입)와 쉽게 통합됩니다. 또한 체인 기반 인증, 사용자 지정 옵션, 재시도 정책, 로깅 및 오류 처리 기능을 제공하여 안정적이고 유지보수 가능한 Azure 인증 코드를 작성할 수 있도록 지원합니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/microsoft/agent-skills/tree/main/.github/plugins/azure-sdk-dotnet/skills/azure-identity-dotnet

Installed? Explore more 라이팅 & 에디팅 skills: steipete/notion, langchain-ai/langchain, bytedance/podcast-generation · View all 6 →

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

.NET용 Azure Identity 라이브러리

Microsoft Entra ID를 사용하여 Azure SDK 클라이언트를 인증하는 라이브러리입니다.

설치

dotnet add package Azure.Identity

# ASP.NET Core 통합을 위한 경우
dotnet add package Microsoft.Extensions.Azure

# 브로커 인증 및 Visual Studio Code 자격 증명 지원을 위한 경우
dotnet add package Azure.Identity.Broker

환경 변수

비밀을 사용한 서비스 주체

AZURE_CLIENT_ID=<application-client-id>
AZURE_TENANT_ID=<directory-tenant-id>
AZURE_CLIENT_SECRET=<client-secret-value>

인증서를 사용한 서비스 주체

AZURE_CLIENT_ID=<application-client-id>
AZURE_TENANT_ID=<directory-tenant-id>
AZURE_CLIENT_CERTIFICATE_PATH=<path-to-pfx-or-pem>
AZURE_CLIENT_CERTIFICATE_PASSWORD=<certificate-password>  # 선택 사항

관리 ID

AZURE_CLIENT_ID=<user-assigned-managed-identity-client-id>  # 사용자 할당의 경우만

DefaultAzureCredential

대부분의 시나리오에 권장되는 자격 증명입니다. 여러 인증 방법을 순서대로 시도합니다. 현재 자격 증명 체인 순서 및 기본값에 대한 자세한 내용은 DefaultAzureCredential 개요를 참조하세요.

기본 사용법

using Azure.Identity;
using Azure.Storage.Blobs;

var credential = new DefaultAzureCredential();
var blobClient = new BlobServiceClient(
    new Uri("https://myaccount.blob.core.windows.net"),
    credential);

ASP.NET Core 및 의존성 주입

using Azure.Identity;
using Microsoft.Extensions.Azure;

builder.Services.AddAzureClients(clientBuilder =>
{
    clientBuilder.AddBlobServiceClient(
        new Uri("https://myaccount.blob.core.windows.net"));
    clientBuilder.AddSecretClient(
        new Uri("https://myvault.vault.azure.net"));
    
    // 기본적으로 DefaultAzureCredential을 사용합니다.
    clientBuilder.UseCredential(new DefaultAzureCredential());
});

DefaultAzureCredential 사용자 지정

var credential = new DefaultAzureCredential(
    new DefaultAzureCredentialOptions
    {
        ExcludeEnvironmentCredential = true,
        ExcludeManagedIdentityCredential = false,
        ExcludeVisualStudioCredential = false,
        ExcludeAzureCliCredential = false,
        ExcludeInteractiveBrowserCredential = false, // 대화형 사용
        TenantId = "<tenant-id>",
        ManagedIdentityClientId = "<user-assigned-mi-client-id>"
    });

자격 증명 유형

ManagedIdentityCredential (프로덕션)

// 시스템 할당 관리 ID
var credential = new ManagedIdentityCredential(ManagedIdentityId.SystemAssigned);

// 클라이언트 ID로 사용자 할당
var credential = new ManagedIdentityCredential(
    ManagedIdentityId.FromUserAssignedClientId("<client-id>"));

// 리소스 ID로 사용자 할당
var credential = new ManagedIdentityCredential(
    ManagedIdentityId.FromUserAssignedResourceId("<resource-id>"));

// 개체 ID로 사용자 할당
var credential = new ManagedIdentityCredential(
    ManagedIdentityId.FromUserAssignedObjectId("<object-id>"));

ClientSecretCredential

var credential = new ClientSecretCredential(
    tenantId: "<tenant-id>",
    clientId: "<client-id>",
    clientSecret: "<client-secret>");

var client = new SecretClient(
    new Uri("https://myvault.vault.azure.net"),
    credential);

ClientCertificateCredential

var certificate = X509CertificateLoader.LoadCertificateFromFile("MyCertificate.pfx");
var credential = new ClientCertificateCredential(
    tenantId: "<tenant-id>",
    clientId: "<client-id>",
    certificate);

ChainedTokenCredential (사용자 지정 체인)

var credential = new ChainedTokenCredential(
    new ManagedIdentityCredential(),
    new AzureCliCredential());

var client = new SecretClient(
    new Uri("https://myvault.vault.azure.net"),
    credential);

개발자 자격 증명

// Azure CLI
var credential = new AzureCliCredential();

// Azure PowerShell
var credential = new AzurePowerShellCredential();

// Azure Developer CLI (azd)
var credential = new AzureDeveloperCliCredential();

// Visual Studio
var credential = new VisualStudioCredential();

// 대화형 브라우저
var credential = new InteractiveBrowserCredential();

환경 기반 구성

// 프로덕션 및 개발
TokenCredential credential = builder.Environment.IsProduction()
    ? new ManagedIdentityCredential("<client-id>")
    : new DefaultAzureCredential();

소버린 클라우드

var credential = new DefaultAzureCredential(
    new DefaultAzureCredentialOptions
    {
        AuthorityHost = AzureAuthorityHosts.AzureGovernment
    });

// 사용 가능한 기관 호스트:
// AzureAuthorityHosts.AzurePublicCloud (기본값)
// AzureAuthorityHosts.AzureGovernment
// AzureAuthorityHosts.AzureChina

자격 증명 유형 참조

범주자격 증명용도
체인DefaultAzureCredential개발부터 프로덕션까지 미리 구성된 체인
ChainedTokenCredential사용자 지정 자격 증명 체인
Azure 호스팅ManagedIdentityCredentialAzure 관리 ID
WorkloadIdentityCredentialKubernetes 워크로드 ID
EnvironmentCredential환경 변수
서비스 주체ClientSecretCredential클라이언트 ID + 비밀
ClientCertificateCredential클라이언트 ID + 인증서
ClientAssertionCredential서명된 클라이언트 어설션
사용자InteractiveBrowserCredential브라우저 기반 인증
DeviceCodeCredential디바이스 코드 흐름
OnBehalfOfCredential위임된 ID
개발자AzureCliCredentialAzure CLI
AzurePowerShellCredentialAzure PowerShell
AzureDeveloperCliCredentialAzure Developer CLI
VisualStudioCredentialVisual Studio

모범 사례

1. 프로덕션에서 결정적 자격 증명 사용

// 개발
var devCredential = new DefaultAzureCredential();

// 프로덕션 - 특정 자격 증명 사용
var prodCredential = new ManagedIdentityCredential(
    ManagedIdentityId.FromUserAssignedClientId("<client-id>"));

2. 자격 증명 인스턴스 재사용

// 좋음: 여러 클라이언트에서 공유되는 단일 자격 증명 인스턴스
var credential = new DefaultAzureCredential();
var blobClient = new BlobServiceClient(blobUri, credential);
var secretClient = new SecretClient(vaultUri, credential);

3. 재시도 정책 구성

var options = new ManagedIdentityCredentialOptions(
    ManagedIdentityId.FromUserAssignedClientId(clientId))
{
    Retry =
    {
        MaxRetries = 3,
        Delay = TimeSpan.FromSeconds(0.5),
    }
};
var credential = new ManagedIdentityCredential(options);

4. 디버깅을 위한 로깅 활성화

using Azure.Core.Diagnostics;

using AzureEventSourceListener listener = new((args, message) =>
{
    if (args is { EventSource.Name: "Azure-Identity" })
    {
        Console.WriteLine(message);
    }
}, EventLevel.LogAlways);

오류 처리

using Azure.Identity;
using Azure.Security.KeyVault.Secrets;

var client = new SecretClient(
    new Uri("https://myvault.vault.azure.net"),
    new DefaultAzureCredential());

try
{
    KeyVaultSecret secret = await client.GetSecretAsync("secret1");
}
catch (AuthenticationFailedException e)
{
    Console.WriteLine($"인증 실패: {e.Message}");
}
catch (CredentialUnavailableException e)
{
    Console.WriteLine($"자격 증명을 사용할 수 없음: {e.Message}");
}

주요 예외

예외설명
AuthenticationFailedException인증 오류의 기본 예외
CredentialUnavailableException현재 환경에서 자격 증명을 인증할 수 없음
AuthenticationRequiredException대화형 인증 필요

관리 ID 지원

지원되는 Azure 서비스:

  • Azure App Service 및 Azure Functions
  • Azure Arc
  • Azure Cloud Shell
  • Azure Kubernetes Service (AKS)
  • Azure Service Fabric
  • Azure Virtual Machines
  • Azure Virtual Machine Scale Sets

스레드 안전성

모든 자격 증명 구현은 스레드로부터 안전합니다. 단일 자격 증명 인스턴스는 여러 클라이언트 및 스레드에서 안전하게 공유할 수 있습니다.

관련 패키지

패키지용도설치
Azure.Identity인증 (이 라이브러리)dotnet add package Azure.Identity
Microsoft.Extensions.AzureDI 통합dotnet add package Microsoft.Extensions.Azure
Azure.Identity.Broker브로커 인증dotnet add package Azure.Identity.Broker

참조 링크

리소스URL
NuGet 패키지https://www.nuget.org/packages/Azure.Identity
API 참조https://learn.microsoft.com/dotnet/api/azure.identity
자격 증명 체인https://aka.ms/azsdk/net/identity/credential-chains
모범 사례https://learn.microsoft.com/dotnet/azure/sdk/authentication/best-practices
GitHub 소스https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/identity/Azure.Identity

Individual skills in this repo

This repo contains 12 individual skills — each has its own dedicated page.

microsoft/azure-ai-agents-persistent-dotnet

Azure AI Agents Persistent SDK for .NET. Low-level SDK for creating and managing AI agents with threads, messages, runs, and tools. Use for agent CRUD, conversation threads, streaming responses, function calling, file search, and code interpreter. Triggers: "PersistentAgentsClient", "persistent agents", "agent threads", "agent runs", "streaming agents", "function calling agents .NET".

microsoft/azure-ai-document-intelligence-dotnet

Azure AI Document Intelligence SDK for .NET. Extract text, tables, and structured data from documents using prebuilt and custom models. Use for invoice processing, receipt extraction, ID document analysis, and custom document models. Triggers: "Document Intelligence", "DocumentIntelligenceClient", "form recognizer", "invoice extraction", "receipt OCR", "document analysis .NET".

microsoft/azure-ai-openai-dotnet

Azure OpenAI SDK for .NET. Client library for Azure OpenAI and OpenAI services. Use for chat completions, embeddings, image generation, audio transcription, and assistants. Triggers: "Azure OpenAI", "AzureOpenAIClient", "ChatClient", "chat completions .NET", "GPT-4", "embeddings", "DALL-E", "Whisper", "OpenAI .NET".

microsoft/azure-ai-projects-dotnet

Azure AI Projects SDK for .NET. High-level client for Azure AI Foundry projects including agents, connections, datasets, deployments, evaluations, and indexes. Use for AI Foundry project management, versioned agents, and orchestration. Triggers: "AI Projects", "AIProjectClient", "Foundry project", "versioned agents", "evaluations", "datasets", "connections", "deployments .NET".

microsoft/azure-ai-voicelive-dotnet

Azure AI Voice Live SDK for .NET. Build real-time voice AI applications with bidirectional WebSocket communication. Use for voice assistants, conversational AI, real-time speech-to-speech, and voice-enabled chatbots. Triggers: "voice live", "real-time voice", "VoiceLiveClient", "VoiceLiveSession", "voice assistant .NET", "bidirectional audio", "speech-to-speech".

microsoft/azure-eventgrid-dotnet

Azure Event Grid SDK for .NET. Client library for publishing and consuming events with Azure Event Grid. Use for event-driven architectures, pub/sub messaging, CloudEvents, and EventGridEvents. Triggers: "Event Grid", "EventGridPublisherClient", "CloudEvent", "EventGridEvent", "publish events .NET", "event-driven", "pub/sub".

microsoft/azure-eventhub-dotnet

Azure Event Hubs SDK for .NET. Use for high-throughput event streaming: sending events (EventHubProducerClient, EventHubBufferedProducerClient), receiving events (EventProcessorClient with checkpointing), partition management, and real-time data ingestion. Triggers: "Event Hubs", "event streaming", "EventHubProducerClient", "EventProcessorClient", "send events", "receive events", "checkpointing", "partition".

microsoft/azure-kusto-graph

Build and query Kusto graphs from natural language. Covers transient graphs (make-graph), persistent graph models/snapshots, pattern matching (graph-match), shortest paths, connected components, and graph-to-table export. Generates the edges-first thinking: define edges, define node lookups, union, make-graph. WHEN: make-graph, graph-match, graph-shortest-paths, graph-to-table, graph-mark-components, persistent graph, graph model, graph snapshot, build a graph from data, find paths between nodes, pattern matching in graph, connected components, transient graph, Kusto graph, KQL graph.

microsoft/azure-kusto-irql

Compose IRQL (Incident Response Query Language) queries for Kusto cybersecurity investigations. Translates natural language hunting questions into composable IRQL pipelines using Get_*, Extract_*, and Enrich_* functions. WHEN: IRQL query, security hunt, threat hunting KQL, incident response query, compose hunting pipeline, failed logins, phishing investigation, lateral movement, process execution, file creation events.

microsoft/azure-kusto-irql-graph

Apply IRQL graph functions to KQL or IRQL query results for Kusto Explorer visualization. Generates Lift_To_Graph mappings and composes Graph_Render_View, Graph_Fold_By_Property, Extract_Node_*, Enrich_Node_*, and Enrich_Graph_* calls. Accepts a supplied query or limited basic natural-language source request; it is not a general natural-language-to-KQL/IRQL skill. WHEN: Lift_To_Graph, Graph_Render_View, Graph_Fold_By_Property, IRQL graph enrichment, graph mapping for existing query results, icon-decorated graph, fold graph nodes. Use azure-kusto-graph for native make-graph analysis, graph-match, shortest paths, components, or persistent graphs.

microsoft/azure-local

Plan, deploy, operate, and troubleshoot Azure Local (formerly Azure Stack HCI): sizing and prerequisites, Arc registration, lifecycle updates, workloads (Azure Local VMs, AKS on Azure Local, images, disks, logical networks), SDN and network security, and failure triage — starting read-only and confirming before risky changes. WHEN: Azure Local, Azure Stack HCI, Arc resource bridge, custom location, Azure Local VM, Arc VM, AKS on Azure Local, AKS hybrid, SDN, Lifecycle Manager, Azure Local update, disconnected site.

microsoft/azure-local-multi-rack

Plan, deploy, operate, and troubleshoot multi-rack (rack scale) deployments of Azure Local — preintegrated racks scaling to hundreds of machines, built on Network Fabric Controller, Cluster Manager, SAN storage, and managed network fabric. Use for the Microsoft.NetworkCloud and Microsoft.ManagedNetworkFabric control plane. NOT for standard 1-16 node Azure Local, and NOT for rack-aware clusters (two racks as availability zones, up to 8 nodes, synchronous replication) — those are standard scale. WHEN: multi-rack, rack scale Azure Local, aggregation rack, compute rack, Network Fabric Controller, NFC, Cluster Manager, network fabric, isolation domain, az networkcloud, az networkfabric, multi-rack logical network, multi-rack Arc VM.

관련 스킬