Quickstart: Authenticate .NET Applications with Azure Identity
This guide will walk you through the steps to enable your .NET applications to authenticate with Azure services using the Azure Identity client library. We'll cover how to get started, set up your environment, and write your first authentication code.
Table of Contents
Introduction
The Azure Identity library for .NET simplifies the process of obtaining Azure Active Directory (Azure AD) tokens for authenticating your applications to Azure services. It offers a DefaultAzureCredential class that automatically attempts to authenticate using various methods based on the environment your application is running in, such as environment variables, managed identity, and Visual Studio/Azure CLI credentials.
Prerequisites
- .NET SDK installed (version 6.0 or later recommended).
- An Azure subscription.
- An Azure AD application registration (if using Service Principal credentials).
- Azure CLI installed and logged in (optional, for local development testing).
Installation
To use the Azure Identity library in your .NET project, install the necessary NuGet packages:
dotnet add package Azure.Identity
Authentication Options
Using DefaultAzureCredential
The DefaultAzureCredential is the recommended way to authenticate in most scenarios. It tries a variety of credential types in order, making it easy to develop locally and deploy to Azure without changing your code.
Here's how it works:
- Environment Variables: Checks for specific environment variables containing credentials.
- Managed Identity: If running on Azure (e.g., App Service, Azure Functions, VMs with managed identity enabled), it will use the managed identity.
- Workload Identity: For Kubernetes environments.
- Visual Studio: If you are logged into Visual Studio.
- Azure CLI: If you are logged in via the Azure CLI (`az login`).
Using ClientCredential
For scenarios where you need to explicitly provide credentials for a Service Principal, you can use ClientCredential. This is often used in server-to-server communication where there's no interactive user or managed identity available.
You'll need your Azure AD tenant ID, client ID (application ID), and a client secret or certificate.
Example Usage
The following example demonstrates how to use DefaultAzureCredential to authenticate to Azure Blob Storage. You can replace BlobServiceClient with any other Azure SDK client that supports token credential authentication.
Program.cs
using Azure;
using Azure.Identity;
using Azure.Storage.Blobs;
using System;
using System.Threading.Tasks;
public class Program
{
public static async Task Main(string[] args)
{
// Replace with your Azure Storage account name
string accountName = "YOUR_STORAGE_ACCOUNT_NAME";
string blobContainerName = "YOUR_CONTAINER_NAME"; // Optional: if you need to interact with a specific container
// Authenticate using DefaultAzureCredential
// This will automatically look for credentials in the environment
// (e.g., AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, or logged in via Azure CLI/VS)
TokenCredential credential = new DefaultAzureCredential();
// Construct the BlobServiceClient with the endpoint and credential
// The endpoint format is "https://{accountName}.blob.core.windows.net"
Uri endpoint = new Uri($"https://{accountName}.blob.core.windows.net");
BlobServiceClient blobServiceClient = new BlobServiceClient(endpoint, credential);
Console.WriteLine($"Successfully authenticated using DefaultAzureCredential.");
Console.WriteLine($"Accessing Blob Storage account: {accountName}");
try
{
// Example: List containers in the storage account
Console.WriteLine("\nListing containers:");
await foreach (var container in blobServiceClient.GetBlobContainersAsync())
{
Console.WriteLine($"- {container.Name}");
}
// If you need to work with a specific container:
// BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(blobContainerName);
// Console.WriteLine($"\nAccessing container: {blobContainerName}");
}
catch (RequestFailedException ex)
{
Console.WriteLine($"Error: {ex.Message}");
Console.WriteLine("Ensure your application has the necessary permissions to access the Azure resource.");
}
catch (Exception ex)
{
Console.WriteLine($"An unexpected error occurred: {ex.Message}");
}
}
}
To run this example:
- Ensure you have installed the
Azure.IdentityNuGet package. - Replace
YOUR_STORAGE_ACCOUNT_NAMEandYOUR_CONTAINER_NAMEwith your actual Azure Storage details. - Configure your environment for authentication. For local development, you can log in via Azure CLI:
Or set the following environment variables:az loginAZURE_TENANT_ID: Your Azure AD tenant ID.AZURE_CLIENT_ID: Your Azure AD application (client) ID.AZURE_CLIENT_SECRET: Your Azure AD application client secret.
- Ensure the identity used for authentication (your user, service principal, or managed identity) has appropriate permissions (e.g., "Storage Blob Data Reader" or "Storage Blob Data Contributor") for the target Azure Storage account.
az login command is often the simplest way to authenticate with DefaultAzureCredential.
Next Steps
- Explore other Azure SDK clients that integrate with Azure Identity.
- Learn more about configuring authentication for specific Azure services.
- Understand how to use managed identities for enhanced security.
- Refer to the API Reference for detailed information on available classes and methods.