Community寫作與編輯github.com

microsoft/azure-identity-dotnet

Azure Identity 程式庫 for .NET。使用 Microsoft Entra ID 為 Azure SDK 用戶端提供驗證功能。用於 DefaultAzureCredential、受控識別、服務主體和開發人員認證。觸發詞:「Azure Identity」、「DefaultAzureCredential」、「ManagedIdentityCredential」、「ClientSecretCredential」、「authentication .NET」、「Azure auth」、「credential chain」。

azure-identity-dotnet 是什麼?

此技能提供適用於 .NET 的 Azure Identity 程式庫,這是一個統一的驗證程式庫,可簡化使用 Microsoft Entra ID 進行 Azure SDK 用戶端驗證的過程。它能讓開發人員輕鬆使用 DefaultAzureCredential(建議用於開發到生產環境的順暢過渡)、ManagedIdentityCredential(適用於 Azure 託管的生產工作負載,如 App Service 和 AKS)、ClientSecretCredential(服務主體)以及多種開發人員認證(如 Azure CLI、PowerShell 和 Visual Studio)。此技能透過 dotnet add package 命令安裝,與 ASP.NET Core 的相依性注入整合,支援鏈結認證(ChainedTokenCredential)自訂驗證流程,並提供用於 Sovereign Clouds(如 Azure Government)的選項。最佳實務包括在生產環境中使用確定性認證、重複使用認證執行個體以避免資源耗盡、設定重試原則以提升韌性,以及啟用 AzureEventSourceListener 進行偵錯記錄。錯誤處理會擷取 AuthenticationFailedException 和 CredentialUnavailableException,以妥善管理驗證失敗和環境不相容問題。

相容平台~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 的新對話。

說明文件

適用於 .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=<應用程式-用戶端-識別碼>
AZURE_TENANT_ID=<目錄-租用戶-識別碼>
AZURE_CLIENT_SECRET=<用戶端-祕密-值>

服務主體搭配憑證

AZURE_CLIENT_ID=<應用程式-用戶端-識別碼>
AZURE_TENANT_ID=<目錄-租用戶-識別碼>
AZURE_CLIENT_CERTIFICATE_PATH=<pfx-或-pem-檔案路徑>
AZURE_CLIENT_CERTIFICATE_PASSWORD=<憑證密碼>  # 選填

受控識別

AZURE_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 = "<租用戶-識別碼>",
        ManagedIdentityClientId = "<使用者指派受控識別的用戶端識別碼>"
    });

認證類型

ManagedIdentityCredential (生產環境)

// 系統指派受控識別
var credential = new ManagedIdentityCredential(ManagedIdentityId.SystemAssigned);

// 依用戶端識別碼的使用者指派
var credential = new ManagedIdentityCredential(
    ManagedIdentityId.FromUserAssignedClientId("<用戶端-識別碼>"));

// 依資源識別碼的使用者指派
var credential = new ManagedIdentityCredential(
    ManagedIdentityId.FromUserAssignedResourceId("<資源-識別碼>"));

// 依物件識別碼的使用者指派
var credential = new ManagedIdentityCredential(
    ManagedIdentityId.FromUserAssignedObjectId("<物件-識別碼>"));

ClientSecretCredential

var credential = new ClientSecretCredential(
    tenantId: "<租用戶-識別碼>",
    clientId: "<用戶端-識別碼>",
    clientSecret: "<用戶端-祕密>");

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

ClientCertificateCredential

var certificate = X509CertificateLoader.LoadCertificateFromFile("MyCertificate.pfx");
var credential = new ClientCertificateCredential(
    tenantId: "<租用戶-識別碼>",
    clientId: "<用戶端-識別碼>",
    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("<用戶端-識別碼>")
    : new DefaultAzureCredential();

主權雲端

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

// 可用的授權主機:
// AzureAuthorityHosts.AzurePublicCloud (預設)
// AzureAuthorityHosts.AzureGovernment
// AzureAuthorityHosts.AzureChina

認證類型參考

類別認證用途
鏈結DefaultAzureCredential從開發到生產的預設鏈結
ChainedTokenCredential自訂認證鏈結
Azure 託管ManagedIdentityCredentialAzure 受控識別
WorkloadIdentityCredentialKubernetes 工作負載身分識別
EnvironmentCredential環境變數
服務主體ClientSecretCredential用戶端識別碼 + 祕密
ClientCertificateCredential用戶端識別碼 + 憑證
ClientAssertionCredential已簽署用戶端判斷提示
使用者InteractiveBrowserCredential瀏覽器為基礎的驗證
DeviceCodeCredential裝置代碼流程
OnBehalfOfCredential委派身分識別
開發人員AzureCliCredentialAzure CLI
AzurePowerShellCredentialAzure PowerShell
AzureDeveloperCliCredentialAzure Developer CLI
VisualStudioCredentialVisual Studio

最佳實務

1. 在生產環境中使用確定性認證

// 開發環境
var devCredential = new DefaultAzureCredential();

// 生產環境 - 使用特定認證
var prodCredential = new ManagedIdentityCredential(
    ManagedIdentityId.FromUserAssignedClientId("<用戶端-識別碼>"));

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.

相關技能