Communityライティング&編集github.com

microsoft/azure-identity-dotnet

Azure Identityライブラリ for .NET。Microsoft Entra IDを使用してAzure SDKクライアントを認証するライブラリ。DefaultAzureCredential、マネージドID、サービスプリンシパル、開発者資格情報に使用。トリガー:「Azure Identity」「DefaultAzureCredential」「ManagedIdentityCredential」「ClientSecretCredential」「authentication .NET」「Azure auth」「credential chain」。

azure-identity-dotnet とは?

このスキルは、Azure Identity for .NETライブラリの包括的なリファレンスを提供し、Azure SDKクライアントのMicrosoft Entra ID認証を容易にします。DefaultAzureCredentialによる複数の認証方法の自動チェーン、ManagedIdentityCredentialによるAzureホスト型アプリケーションのシームレスな認証、ClientSecretCredentialによるサービスプリンシパル認証、開発用のInteractiveBrowserCredentialやAzureCliCredentialなど、すべての主要な資格情報タイプをカバーしています。ASP.NET Coreの依存性注入との統合、サブジェクトクラウド(Azure Government、Azure China)のサポート、カスタム資格情報チェーンの構築方法も詳しく説明しています。本番環境では決定論的な資格情報を使用し、シングルトンパターンで資格情報インスタンスを再利用し、トラブルシューティングのためにログ記録を有効にするというベストプラクティスを強調しています。また、Azure Key Vaultを使用したエラーハンドリングのサンプルや、AuthenticationFailedExceptionなどの主要な例外のリファレンスも含まれています。このスキルは、Visual Studio、VS Code、JetBrains Rider、Cline、Windsurfなどの主要な開発環境および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に質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

.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=<アプリケーションクライアントID>
AZURE_TENANT_ID=<ディレクトリテナントID>
AZURE_CLIENT_SECRET=<クライアントシークレット値>

証明書を使用したサービスプリンシパル

AZURE_CLIENT_ID=<アプリケーションクライアントID>
AZURE_TENANT_ID=<ディレクトリテナントID>
AZURE_CLIENT_CERTIFICATE_PATH=<pfxまたはpemファイルへのパス>
AZURE_CLIENT_CERTIFICATE_PASSWORD=<証明書パスワード>  # オプション

マネージドID

AZURE_CLIENT_ID=<ユーザー割り当てマネージドIDのクライアント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 = "<テナントID>",
        ManagedIdentityClientId = "<ユーザー割り当てMIクライアントID>"
    });

資格情報の種類

ManagedIdentityCredential(本番環境)

// システム割り当てマネージドID
var credential = new ManagedIdentityCredential(ManagedIdentityId.SystemAssigned);

// クライアントIDによるユーザー割り当て
var credential = new ManagedIdentityCredential(
    ManagedIdentityId.FromUserAssignedClientId("<クライアントID>"));

// リソースIDによるユーザー割り当て
var credential = new ManagedIdentityCredential(
    ManagedIdentityId.FromUserAssignedResourceId("<リソースID>"));

// オブジェクトIDによるユーザー割り当て
var credential = new ManagedIdentityCredential(
    ManagedIdentityId.FromUserAssignedObjectId("<オブジェクトID>"));

ClientSecretCredential

var credential = new ClientSecretCredential(
    tenantId: "<テナントID>",
    clientId: "<クライアントID>",
    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: "<テナントID>",
    clientId: "<クライアント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("<クライアントID>")
    : new DefaultAzureCredential();

Sovereignクラウド

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

// 利用可能なAuthorityHost:
// 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("<クライアント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.

関連スキル