Community写作与编辑github.com

microsoft/azure-identity-dotnet

Azure Identity 库,用于 .NET。使用 Microsoft Entra ID 为 Azure SDK 客户端提供身份验证。支持 DefaultAzureCredential、托管标识、服务主体和开发人员凭据。

azure-identity-dotnet 是什么?

Azure Identity for .NET 是一个核心身份验证库,用于 .NET 应用程序通过 Microsoft Entra ID 对 Azure SDK 客户端进行身份验证。它提供统一的凭据链(如 DefaultAzureCredential)以及多种专用凭据类型(如 ManagedIdentityCredential、ClientSecretCredential),覆盖从本地开发到生产环境的常见 Azure 身份验证需求。该技能详细介绍了安装步骤、环境变量配置、常用凭据在 .NET 代码中的使用方式(包括 ASP.NET Core 依赖注入集成),还涵盖了错误处理、最佳实践、线程安全性和相关包引用。支持的平台包括 .NET 应用程序,可作为 Claude Code、Cursor、Codex 等 AI 编码代理的配置参考文档,帮助开发者快速选择合适的凭据类型并正确集成。

兼容平台~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 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

Azure Identity 库 for .NET

使用 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>  # 可选

托管标识

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(生产环境)

// 系统分配托管标识
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();

基于环境的配置

// 生产环境 vs 开发环境
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 托管标识
WorkloadIdentityCredentialKubernetes 工作负载标识
EnvironmentCredential环境变量
服务主体ClientSecretCredential客户端 ID + 机密
ClientCertificateCredential客户端 ID + 证书
ClientAssertionCredential已签名的客户端断言
用户InteractiveBrowserCredential基于浏览器的身份验证
DeviceCodeCredential设备代码流
OnBehalfOfCredential委托标识
开发人员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需要交互式身份验证

托管标识支持

支持的 Azure 服务:

  • Azure App Service 和 Azure Functions
  • Azure Arc
  • Azure Cloud Shell
  • Azure Kubernetes Service (AKS)
  • Azure Service Fabric
  • Azure 虚拟机
  • Azure 虚拟机规模集

线程安全

所有凭据实现都是线程安全的。单个凭据实例可以安全地在多个客户端和线程之间共享。

相关包

包用途安装
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.

相关技能