CommunityRédaction et éditiongithub.com

microsoft/azure-identity-dotnet

Bibliothèque Azure Identity pour .NET. Bibliothèque d'authentification pour les clients SDK Azure utilisant Microsoft Entra ID. Utilisez pour DefaultAzureCredential, les identités managées, les principaux de service et les informations d'identification des développeurs. Déclencheurs : "Azure Identity", "DefaultAzureCredential", "ManagedIdentityCredential", "ClientSecretCredential", "authentification .NET", "Azure auth", "chaîne d'informations d'identification".

Qu'est-ce que azure-identity-dotnet ?

Cette compétence fournit des connaissances complètes sur la bibliothèque Azure Identity pour .NET, essentielle pour authentifier les applications .NET auprès des services Azure via Microsoft Entra ID. Elle explique en détail le fonctionnement de DefaultAzureCredential, qui tente automatiquement plusieurs méthodes d'authentification dans un ordre prédéfini, facilitant ainsi la transition du développement à la production. La compétence couvre tous les types d'informations d'identification, y compris ManagedIdentityCredential pour les environnements Azure hébergés, ClientSecretCredential et ClientCertificateCredential pour les principaux de service, ainsi que les informations d'identification pour les développeurs comme AzureCliCredential et InteractiveBrowserCredential. Elle inclut également des instructions sur les variables d'environnement, la personnalisation des chaînes d'informations d'identification, la gestion des erreurs, les meilleures pratiques de performance et de sécurité, ainsi que les nuages souverains. Cette compétence est optimisée pour les agents IA travaillant avec les SDK Azure et le développement .NET, leur permettant de générer du code d'authentification correct et sécurisé.

Compatible avec~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 Rédaction et édition skills: steipete/notion, langchain-ai/langchain, bytedance/podcast-generation · View all 6 →

Demander à votre IA préférée

Ouvre une nouvelle conversation avec cette compétence d'agent déjà préchargée.

Documentation

Bibliothèque Azure Identity pour .NET

Bibliothèque d'authentification pour les clients SDK Azure utilisant Microsoft Entra ID.

Installation

dotnet add package Azure.Identity

# Pour l'intégration ASP.NET Core
dotnet add package Microsoft.Extensions.Azure

# Pour l'authentification intermédiée et la prise en charge des informations d'identification Visual Studio Code
dotnet add package Azure.Identity.Broker

Variables d'environnement

Principal de service avec secret

AZURE_CLIENT_ID=<identifiant-client-application>
AZURE_TENANT_ID=<identifiant-locataire-annuaire>
AZURE_CLIENT_SECRET=<valeur-secret-client>

Principal de service avec certificat

AZURE_CLIENT_ID=<identifiant-client-application>
AZURE_TENANT_ID=<identifiant-locataire-annuaire>
AZURE_CLIENT_CERTIFICATE_PATH=<chemin-vers-fichier-pfx-ou-pem>
AZURE_CLIENT_CERTIFICATE_PASSWORD=<mot-de-passe-certificat>  # Optionnel

Identité managée

AZURE_CLIENT_ID=<identifiant-client-identite-managee-attribuee-utilisateur>  # Uniquement pour attribuée à l'utilisateur

DefaultAzureCredential

L'information d'identification recommandée pour la plupart des scénarios. Essaie plusieurs méthodes d'authentification dans l'ordre. Voir Vue d'ensemble de DefaultAzureCredential pour l'ordre actuel de la chaîne d'informations d'identification et les valeurs par défaut.

Utilisation de base

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 avec injection de dépendances

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"));
    
    // Utilise DefaultAzureCredential par défaut
    clientBuilder.UseCredential(new DefaultAzureCredential());
});

Personnalisation de DefaultAzureCredential

var credential = new DefaultAzureCredential(
    new DefaultAzureCredentialOptions
    {
        ExcludeEnvironmentCredential = true,
        ExcludeManagedIdentityCredential = false,
        ExcludeVisualStudioCredential = false,
        ExcludeAzureCliCredential = false,
        ExcludeInteractiveBrowserCredential = false, // Activer l'interactif
        TenantId = "<identifiant-locataire>",
        ManagedIdentityClientId = "<identifiant-client-mi-attribuee-utilisateur>"
    });

Types d'informations d'identification

ManagedIdentityCredential (Production)

// Identité managée attribuée par le système
var credential = new ManagedIdentityCredential(ManagedIdentityId.SystemAssigned);

// Attribuée à l'utilisateur par identifiant client
var credential = new ManagedIdentityCredential(
    ManagedIdentityId.FromUserAssignedClientId("<identifiant-client>"));

// Attribuée à l'utilisateur par identifiant de ressource
var credential = new ManagedIdentityCredential(
    ManagedIdentityId.FromUserAssignedResourceId("<identifiant-ressource>"));

// Attribuée à l'utilisateur par identifiant d'objet
var credential = new ManagedIdentityCredential(
    ManagedIdentityId.FromUserAssignedObjectId("<identifiant-objet>"));

ClientSecretCredential

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

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

ClientCertificateCredential

var certificate = X509CertificateLoader.LoadCertificateFromFile("MonCertificat.pfx");
var credential = new ClientCertificateCredential(
    tenantId: "<identifiant-locataire>",
    clientId: "<identifiant-client>",
    certificate);

ChainedTokenCredential (Chaîne personnalisée)

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

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

Informations d'identification pour les développeurs

// 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();

// Navigateur interactif
var credential = new InteractiveBrowserCredential();

Configuration basée sur l'environnement

// Production vs Développement
TokenCredential credential = builder.Environment.IsProduction()
    ? new ManagedIdentityCredential("<identifiant-client>")
    : new DefaultAzureCredential();

Nuages souverains

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

// Hôtes d'autorité disponibles :
// AzureAuthorityHosts.AzurePublicCloud (par défaut)
// AzureAuthorityHosts.AzureGovernment
// AzureAuthorityHosts.AzureChina

Référence des types d'informations d'identification

CatégorieInformation d'identificationObjectif
ChaînesDefaultAzureCredentialChaîne préconfigurée pour le développement à la production
ChainedTokenCredentialChaîne d'informations d'identification personnalisée
Hébergé AzureManagedIdentityCredentialIdentité managée Azure
WorkloadIdentityCredentialIdentité de charge de travail Kubernetes
EnvironmentCredentialVariables d'environnement
Principal de serviceClientSecretCredentialIdentifiant client + secret
ClientCertificateCredentialIdentifiant client + certificat
ClientAssertionCredentialAssertion client signée
UtilisateurInteractiveBrowserCredentialAuthentification par navigateur
DeviceCodeCredentialFlux de code d'appareil
OnBehalfOfCredentialIdentité déléguée
DéveloppeurAzureCliCredentialAzure CLI
AzurePowerShellCredentialAzure PowerShell
AzureDeveloperCliCredentialAzure Developer CLI
VisualStudioCredentialVisual Studio

Meilleures pratiques

1. Utiliser des informations d'identification déterministes en production

// Développement
var devCredential = new DefaultAzureCredential();

// Production - utiliser une information d'identification spécifique
var prodCredential = new ManagedIdentityCredential(
    ManagedIdentityId.FromUserAssignedClientId("<identifiant-client>"));

2. Réutiliser les instances d'informations d'identification

// Bon : Instance d'information d'identification unique partagée entre les clients
var credential = new DefaultAzureCredential();
var blobClient = new BlobServiceClient(blobUri, credential);
var secretClient = new SecretClient(vaultUri, credential);

3. Configurer les stratégies de nouvelle tentative

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

4. Activer la journalisation pour le débogage

using Azure.Core.Diagnostics;

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

Gestion des erreurs

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($"Échec d'authentification : {e.Message}");
}
catch (CredentialUnavailableException e)
{
    Console.WriteLine($"Information d'identification non disponible : {e.Message}");
}

Exceptions clés

ExceptionDescription
AuthenticationFailedExceptionException de base pour les erreurs d'authentification
CredentialUnavailableExceptionL'information d'identification ne peut pas authentifier dans l'environnement actuel
AuthenticationRequiredExceptionUne authentification interactive est requise

Prise en charge de l'identité managée

Services Azure pris en charge :

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

Sécurité des threads

Toutes les implémentations d'informations d'identification sont thread-safe. Une seule instance d'information d'identification peut être partagée en toute sécurité entre plusieurs clients et threads.

Packages associés

PackageObjectifInstallation
Azure.IdentityAuthentification (cette bibliothèque)dotnet add package Azure.Identity
Microsoft.Extensions.AzureIntégration DIdotnet add package Microsoft.Extensions.Azure
Azure.Identity.BrokerAuthentification intermédiéedotnet add package Azure.Identity.Broker

Liens de référence

RessourceURL
Package NuGethttps://www.nuget.org/packages/Azure.Identity
Référence APIhttps://learn.microsoft.com/dotnet/api/azure.identity
Chaînes d'informations d'identificationhttps://aka.ms/azsdk/net/identity/credential-chains
Meilleures pratiqueshttps://learn.microsoft.com/dotnet/azure/sdk/authentication/best-practices
Source GitHubhttps://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.

Skills associés