Authenticate Securely to Azure Services
.NET skill for Azure.Identity authentication - DefaultAzureCredential chains, managed identity, and sovereign clouds.
Why it matters
Streamline authentication to Azure services for your .NET applications. This asset simplifies credential management, enabling secure access to resources like Azure Blob Storage and Key Vault.
Outcomes
What it gets done
Manage service principal secrets and certificates for Azure authentication.
Utilize DefaultAzureCredential for seamless development-to-production credential handling.
Integrate with ASP.NET Core applications using dependency injection for Azure clients.
Configure and debug authentication flows with detailed logging and error handling.
Install
Add it to your toolbox
Run in your project directory:
curl -fsSL https://spark.entire.vc/get/ag-azure-identity-dotnet | bash Overview
Azure.Identity (.NET)
.NET skill for Azure.Identity authentication, covering the nine-credential DefaultAzureCredential fallback chain, managed identity and service-principal credentials, custom ChainedTokenCredential chains, sovereign-cloud targeting, and production best practices around deterministic credentials, retries, and logging. Use whenever an Azure SDK client needs to authenticate to Microsoft Entra ID, in local development or Azure-hosted production.
What it does
This skill authenticates Azure SDK clients using Azure.Identity (.NET, stable v1.17.1), Microsoft's library for Microsoft Entra ID (formerly Azure AD) authentication - with optional companion packages for ASP.NET Core dependency injection (Microsoft.Extensions.Azure) and Windows brokered authentication (Azure.Identity.Broker). Its centerpiece is DefaultAzureCredential, the recommended credential for most scenarios, which tries up to nine credential sources in a fixed order - Environment, WorkloadIdentity, ManagedIdentity, VisualStudio, VisualStudioCode, AzureCli, AzurePowerShell, AzureDeveloperCli (all enabled by default), and InteractiveBrowser (disabled by default) - so the same code authenticates seamlessly across local development and Azure-hosted production. It's used directly (new DefaultAzureCredential() passed to any Azure client constructor) or wired into ASP.NET Core's DI container via AddAzureClients/UseCredential. DefaultAzureCredentialOptions lets you exclude specific credential types, set a target tenant ID, or specify a user-assigned managed identity's client ID. Beyond the default chain, it covers individual credential types directly: ManagedIdentityCredential (system-assigned, or user-assigned by client ID or resource ID) for production Azure-hosted workloads; ClientSecretCredential and ClientCertificateCredential for service-principal auth; ChainedTokenCredential for building a custom fallback chain (e.g. managed identity first, Azure CLI as local fallback); and developer credentials (AzureCliCredential, AzurePowerShellCredential, AzureDeveloperCliCredential, VisualStudioCredential, InteractiveBrowserCredential) for local-only use. It shows switching credentials by environment (ManagedIdentityCredential in production, DefaultAzureCredential in development) and targeting sovereign clouds via AuthorityHost (Azure Government, China, Germany, alongside the default public cloud). Best practices cover using deterministic, specific credentials in production rather than the probing default chain, reusing a single credential instance across multiple Azure clients (all credential implementations are thread-safe), configuring retry policies (MaxRetries, Delay) on ManagedIdentityCredentialOptions, and enabling AzureEventSourceListener-based logging scoped to the "Azure-Identity" event source for debugging authentication failures. Error handling distinguishes AuthenticationFailedException (authentication failed), CredentialUnavailableException (this credential type can't authenticate in the current environment - expected when probing a chain), and AuthenticationRequiredException (interactive auth needed). Managed identity is supported across Azure App Service/Functions, Azure Arc, Cloud Shell, AKS, Service Fabric, and Virtual Machines/Scale Sets.
When to use - and when NOT to
Use this skill whenever an Azure SDK client (Blob Storage, Key Vault, Cosmos DB, and others) needs to authenticate to Microsoft Entra ID - whether via the probing DefaultAzureCredential for code that must work unmodified across local dev and Azure-hosted production, or a specific credential type when the deployment target is known and deterministic behavior matters. It is not for authenticating to non-Azure/non-Entra-ID services, and relying on the full DefaultAzureCredential probing chain in production is explicitly discouraged in favor of a specific, deterministic credential like ManagedIdentityCredential. It also covers delegated on-behalf-of auth (OnBehalfOfCredential), device-code flow for input-constrained devices (DeviceCodeCredential), and Kubernetes workload identity (WorkloadIdentityCredential) for scenarios beyond the default chain.
Inputs and outputs
Input is credential configuration (environment variables, a managed identity client ID, a service-principal secret/certificate, or explicit exclusion flags). Output is a TokenCredential instance passed to any Azure SDK client constructor, which internally acquires and refreshes access tokens as needed.
Integrations
Built as Azure.Identity, integrating with every Azure SDK client library that accepts a TokenCredential (Blob Storage, Key Vault, Cosmos DB, etc.), with Microsoft.Extensions.Azure for ASP.NET Core DI wiring and Azure.Identity.Broker for Windows-brokered authentication.
dotnet add package Azure.Identity
Who it's for
.NET developers authenticating any Azure SDK client to Microsoft Entra ID, who need code that works across local development and Azure-hosted production, or deterministic, production-specific credential selection with proper retry and logging.
Source README
Azure.Identity (.NET)
Authentication library for Azure SDK clients using Microsoft Entra ID (formerly Azure AD).
Installation
dotnet add package Azure.Identity
### For ASP.NET Core
dotnet add package Microsoft.Extensions.Azure
### For brokered authentication (Windows)
dotnet add package Azure.Identity.Broker
Current Versions: Stable v1.17.1, Preview v1.18.0-beta.2
Environment Variables
Service Principal with Secret
AZURE_CLIENT_ID=<application-client-id>
AZURE_TENANT_ID=<directory-tenant-id>
AZURE_CLIENT_SECRET=<client-secret-value>
Service Principal with Certificate
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> # Optional
Managed Identity
AZURE_CLIENT_ID=<user-assigned-managed-identity-client-id> # Only for user-assigned
DefaultAzureCredential
The recommended credential for most scenarios. Tries multiple authentication methods in order:
| Order | Credential | Enabled by Default |
|---|---|---|
| 1 | EnvironmentCredential | Yes |
| 2 | WorkloadIdentityCredential | Yes |
| 3 | ManagedIdentityCredential | Yes |
| 4 | VisualStudioCredential | Yes |
| 5 | VisualStudioCodeCredential | Yes |
| 6 | AzureCliCredential | Yes |
| 7 | AzurePowerShellCredential | Yes |
| 8 | AzureDeveloperCliCredential | Yes |
| 9 | InteractiveBrowserCredential | No |
Basic Usage
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 with Dependency Injection
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"));
// Uses DefaultAzureCredential by default
clientBuilder.UseCredential(new DefaultAzureCredential());
});
Customizing DefaultAzureCredential
var credential = new DefaultAzureCredential(
new DefaultAzureCredentialOptions
{
ExcludeEnvironmentCredential = true,
ExcludeManagedIdentityCredential = false,
ExcludeVisualStudioCredential = false,
ExcludeAzureCliCredential = false,
ExcludeInteractiveBrowserCredential = false, // Enable interactive
TenantId = "<tenant-id>",
ManagedIdentityClientId = "<user-assigned-mi-client-id>"
});
Credential Types
ManagedIdentityCredential (Production)
// System-assigned managed identity
var credential = new ManagedIdentityCredential(ManagedIdentityId.SystemAssigned);
// User-assigned by client ID
var credential = new ManagedIdentityCredential(
ManagedIdentityId.FromUserAssignedClientId("<client-id>"));
// User-assigned by resource ID
var credential = new ManagedIdentityCredential(
ManagedIdentityId.FromUserAssignedResourceId("<resource-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 (Custom Chain)
var credential = new ChainedTokenCredential(
new ManagedIdentityCredential(),
new AzureCliCredential());
var client = new SecretClient(
new Uri("https://myvault.vault.azure.net"),
credential);
Developer Credentials
// 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();
// Interactive Browser
var credential = new InteractiveBrowserCredential();
Environment-Based Configuration
// Production vs Development
TokenCredential credential = builder.Environment.IsProduction()
? new ManagedIdentityCredential("<client-id>")
: new DefaultAzureCredential();
Sovereign Clouds
var credential = new DefaultAzureCredential(
new DefaultAzureCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzureGovernment
});
// Available authority hosts:
// AzureAuthorityHosts.AzurePublicCloud (default)
// AzureAuthorityHosts.AzureGovernment
// AzureAuthorityHosts.AzureChina
// AzureAuthorityHosts.AzureGermany
Credential Types Reference
| Category | Credential | Purpose |
|---|---|---|
| Chains | DefaultAzureCredential |
Preconfigured chain for dev-to-prod |
ChainedTokenCredential |
Custom credential chain | |
| Azure-Hosted | ManagedIdentityCredential |
Azure managed identity |
WorkloadIdentityCredential |
Kubernetes workload identity | |
EnvironmentCredential |
Environment variables | |
| Service Principal | ClientSecretCredential |
Client ID + secret |
ClientCertificateCredential |
Client ID + certificate | |
ClientAssertionCredential |
Signed client assertion | |
| User | InteractiveBrowserCredential |
Browser-based auth |
DeviceCodeCredential |
Device code flow | |
OnBehalfOfCredential |
Delegated identity | |
| Developer | AzureCliCredential |
Azure CLI |
AzurePowerShellCredential |
Azure PowerShell | |
AzureDeveloperCliCredential |
Azure Developer CLI | |
VisualStudioCredential |
Visual Studio |
Best Practices
1. Use Deterministic Credentials in Production
// Development
var devCredential = new DefaultAzureCredential();
// Production - use specific credential
var prodCredential = new ManagedIdentityCredential("<client-id>");
2. Reuse Credential Instances
// Good: Single credential instance shared across clients
var credential = new DefaultAzureCredential();
var blobClient = new BlobServiceClient(blobUri, credential);
var secretClient = new SecretClient(vaultUri, credential);
3. Configure Retry Policies
var options = new ManagedIdentityCredentialOptions(
ManagedIdentityId.FromUserAssignedClientId(clientId))
{
Retry =
{
MaxRetries = 3,
Delay = TimeSpan.FromSeconds(0.5),
}
};
var credential = new ManagedIdentityCredential(options);
4. Enable Logging for Debugging
using Azure.Core.Diagnostics;
using AzureEventSourceListener listener = new((args, message) =>
{
if (args is { EventSource.Name: "Azure-Identity" })
{
Console.WriteLine(message);
}
}, EventLevel.LogAlways);
Error Handling
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($"Authentication Failed: {e.Message}");
}
catch (CredentialUnavailableException e)
{
Console.WriteLine($"Credential Unavailable: {e.Message}");
}
Key Exceptions
| Exception | Description |
|---|---|
AuthenticationFailedException |
Base exception for authentication errors |
CredentialUnavailableException |
Credential cannot authenticate in current environment |
AuthenticationRequiredException |
Interactive authentication is required |
Managed Identity Support
Supported Azure services:
- Azure App Service and Azure Functions
- Azure Arc
- Azure Cloud Shell
- Azure Kubernetes Service (AKS)
- Azure Service Fabric
- Azure Virtual Machines
- Azure Virtual Machine Scale Sets
Thread Safety
All credential implementations are thread-safe. A single credential instance can be safely shared across multiple clients and threads.
Related SDKs
| SDK | Purpose | Install |
|---|---|---|
Azure.Identity |
Authentication (this SDK) | dotnet add package Azure.Identity |
Microsoft.Extensions.Azure |
DI integration | dotnet add package Microsoft.Extensions.Azure |
Azure.Identity.Broker |
Brokered auth (Windows) | dotnet add package Azure.Identity.Broker |
Reference Links
| Resource | URL |
|---|---|
| NuGet Package | https://www.nuget.org/packages/Azure.Identity |
| API Reference | https://learn.microsoft.com/dotnet/api/azure.identity |
| Credential Chains | https://learn.microsoft.com/dotnet/azure/sdk/authentication/credential-chains |
| Best Practices | https://learn.microsoft.com/dotnet/azure/sdk/authentication/best-practices |
| GitHub Source | https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/identity/Azure.Identity |
When to Use
This skill is applicable to execute the workflow or actions described in the overview.
Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.
FAQ
Common questions
Discussion
Questions & comments · 0
Sign In Sign in to leave a comment.