Introduction to Azure Authentication

Authenticating with Azure services from your JavaScript applications is a critical aspect of building secure and robust solutions. The Azure SDK for JavaScript provides a consistent and flexible set of tools to manage credentials and authorize access to your Azure resources.

This documentation will guide you through the various authentication methods available, how to choose the right credential type for your scenario, and provide practical examples for integrating authentication into your applications.

Understanding Credential Types

The Azure SDK for JavaScript offers several credential types, each suited for different deployment environments and security requirements. The core principle is to abstract the complexity of credential management, allowing you to focus on your application logic.

DefaultAzureCredential

The DefaultAzureCredential is the recommended credential type for most scenarios. It intelligently attempts to authenticate using a variety of methods in a specific order, including:

This flexibility makes it ideal for applications that might be deployed in different environments or for local development workflows.

// Installation // npm install @azure/identity // Usage import { DefaultAzureCredential } from "@azure/identity"; import { BlobServiceClient } from "@azure/storage-blob"; async function authenticateAndUseBlob() { const credential = new DefaultAzureCredential(); const blobServiceClient = new BlobServiceClient("https://your-storage-account-name.blob.core.windows.net", credential); // Now you can use blobServiceClient to interact with Azure Blob Storage console.log("Authenticated with Azure. BlobServiceClient created."); } authenticateAndUseBlob().catch(console.error);

ServicePrincipalCredential

Use ServicePrincipalCredential when you need to authenticate as an Azure service principal. This is commonly used in CI/CD pipelines or when applications run with specific identities that are not tied to a user.

You will need the tenant ID, client ID, and either a client secret or a certificate.

import { ServicePrincipalCredential } from "@azure/identity"; import { SecretClient } from "@azure/keyvault-secrets"; async function authenticateWithServicePrincipal() { const tenantId = process.env.AZURE_TENANT_ID; const clientId = process.env.AZURE_CLIENT_ID; const clientSecret = process.env.AZURE_CLIENT_SECRET; // Or use certificate if (!tenantId || !clientId || !clientSecret) { throw new Error("AZURE_TENANT_ID, AZURE_CLIENT_ID, and AZURE_CLIENT_SECRET must be set."); } const credential = new ServicePrincipalCredential(tenantId, clientId, clientSecret); const client = new SecretClient("https://your-keyvault-name.vault.azure.net", credential); console.log("Authenticated as Service Principal."); // Use the 'client' to interact with Key Vault } authenticateWithServicePrincipal().catch(console.error);

ManagedIdentityCredential

This credential type is used when your application is running on an Azure service that supports Managed Identities (e.g., Azure App Service, Azure Functions, Virtual Machines). It automatically retrieves a token from the Azure Instance Metadata Service.

import { ManagedIdentityCredential } from "@azure/identity"; import { CosmosClient } from "@azure/cosmos"; async function authenticateWithManagedIdentity() { const credential = new ManagedIdentityCredential(); // Defaults to system-assigned managed identity const endpoint = "https://your-cosmosdb-account.documents.azure.com:443/"; const client = new CosmosClient({ endpoint, credential }); console.log("Authenticated using Managed Identity."); // Use the 'client' to interact with Cosmos DB } authenticateWithManagedIdentity().catch(console.error);

ClientSecretCredential

A simpler credential type for authenticating with a client secret, requiring tenant ID, client ID, and client secret.

import { ClientSecretCredential } from "@azure/identity"; import { KeyClient } from "@azure/keyvault-keys"; async function authenticateWithClientSecret() { const tenantId = "YOUR_TENANT_ID"; const clientId = "YOUR_CLIENT_ID"; const clientSecret = "YOUR_CLIENT_SECRET"; const credential = new ClientSecretCredential(tenantId, clientId, clientSecret); const client = new KeyClient("https://your-keyvault-name.vault.azure.net", credential); console.log("Authenticated using Client Secret."); // Use the 'client' to interact with Key Vault Keys } authenticateWithClientSecret().catch(console.error);

InteractiveBrowserCredential

Ideal for Single-Page Applications (SPAs) or applications running in a browser where the user can be prompted to sign in. It leverages Azure AD's interactive authentication flows.

import { InteractiveBrowserCredential } from "@azure/identity"; import { TableClient } from "@azure/data-tables"; async function authenticateWithInteractiveBrowser() { const credential = new InteractiveBrowserCredential(); const client = new TableClient("https://your-storage-account-name.table.core.windows.net", "YourTableName", { credential }); console.log("Authenticated interactively in the browser."); // Use the 'client' to interact with Azure Table Storage } authenticateWithInteractiveBrowser().catch(console.error);

EnvironmentCredential

Reads credentials from environment variables. Useful for applications that are configured via their environment, but don't necessarily have access to managed identities or Azure CLI.

import { EnvironmentCredential } from "@azure/identity"; import { EventHubsClient } from "@azure/event-hubs"; async function authenticateWithEnvironment() { const credential = new EnvironmentCredential(); const fullyQualifiedNamespace = "YOUR_EVENT_HUB_NAMESPACE.servicebus.windows.net"; const eventHubName = "YOUR_EVENT_HUB_NAME"; const client = new EventHubsClient(fullyQualifiedNamespace, eventHubName, credential); console.log("Authenticated using environment variables."); // Use the 'client' to interact with Event Hubs } authenticateWithEnvironment().catch(console.error);

TokenCredential Interface

All credential classes implement the TokenCredential interface, which provides a common method, getToken(scopes). This interface ensures interoperability across different Azure SDK clients. When you pass a credential object to an SDK client constructor, it implicitly uses this interface.

Putting It All Together

Most Azure SDK clients in JavaScript accept a credential object directly in their constructor. The chosen credential type will handle the token acquisition and refreshing automatically.

Refer to the individual service documentation for specific examples using each credential type. The @azure/identity package is the foundation for all authentication operations.

// Common setup for any Azure SDK client using @azure/identity import { DefaultAzureCredential } from "@azure/identity"; import { QueueServiceClient } from "@azure/storage-queue"; async function exampleUsage() { // Initialize credential - DefaultAzureCredential is often the best starting point const credential = new DefaultAzureCredential(); // Replace with your actual Azure Storage Queue service URL const queueServiceUrl = "https://your-storage-account.queue.core.windows.net"; const queueServiceClient = new QueueServiceClient(queueServiceUrl, credential); try { // Example operation: List queues const queues = queueServiceClient.listQueues(); console.log("Successfully connected to Azure Storage Queues."); for await (const queue of queues) { console.log(`- ${queue.name}`); } } catch (error) { console.error("An error occurred:", error); } } exampleUsage();