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.

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

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:

  1. Environment Variables: Checks for specific environment variables containing credentials.
  2. Managed Identity: If running on Azure (e.g., App Service, Azure Functions, VMs with managed identity enabled), it will use the managed identity.
  3. Workload Identity: For Kubernetes environments.
  4. Visual Studio: If you are logged into Visual Studio.
  5. 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:

  1. Ensure you have installed the Azure.Identity NuGet package.
  2. Replace YOUR_STORAGE_ACCOUNT_NAME and YOUR_CONTAINER_NAME with your actual Azure Storage details.
  3. Configure your environment for authentication. For local development, you can log in via Azure CLI:
    az login
    Or set the following environment variables:
    • AZURE_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.
  4. 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.
Tip: When developing locally, using the Azure CLI's az login command is often the simplest way to authenticate with DefaultAzureCredential.

Next Steps

© 2023 Microsoft Corporation. All rights reserved.