Managed Identity Applications provide authentication for applications running on Azure resources like Virtual Machines, App Service, Function Apps, and other Azure services. This eliminates the need to store credentials in code by leveraging Azure's managed identity infrastructure.
Main class for Azure Managed Identity authentication.
/**
* Managed Identity application class for Azure resources
* Automatically detects and uses the appropriate managed identity source
*/
class ManagedIdentityApplication {
constructor(configuration: ManagedIdentityConfiguration);
/**
* Acquires a token using Azure Managed Identity
* Automatically detects the managed identity source (IMDS, App Service, etc.)
*/
acquireToken(request: ManagedIdentityRequestParams): Promise<AuthenticationResult | null>;
}
/**
* Configuration for managed identity applications
*/
type ManagedIdentityConfiguration = {
/** Client capabilities for conditional access */
clientCapabilities?: Array<string>;
/** Parameters for user-assigned managed identity */
managedIdentityIdParams?: ManagedIdentityIdParams;
/** System configuration options */
system?: NodeSystemOptions;
};
/**
* Parameters for user-assigned managed identity
*/
type ManagedIdentityIdParams = {
/** Client ID of the user-assigned managed identity */
userAssignedClientId?: string;
/** Resource ID of the user-assigned managed identity */
userAssignedResourceId?: string;
/** Object ID of the user-assigned managed identity */
userAssignedObjectId?: string;
};
/**
* Request parameters for managed identity token acquisition
*/
type ManagedIdentityRequestParams = {
/** Target resource URI for the token */
resource: string;
/** Claims for conditional access */
claims?: string;
/** Force refresh instead of using cached token */
forceRefresh?: boolean;
};Usage Example:
import { ManagedIdentityApplication } from "@azure/msal-node";
// System-assigned managed identity (default)
const mia = new ManagedIdentityApplication({});
const tokenRequest = {
resource: "https://graph.microsoft.com/"
};
try {
const response = await mia.acquireToken(tokenRequest);
if (response) {
console.log("Access token:", response.accessToken);
console.log("Token expires on:", response.expiresOn);
}
} catch (error) {
console.error("Managed identity authentication failed:", error);
}Default configuration that uses the system-assigned managed identity of the Azure resource.
/**
* Basic configuration for system-assigned managed identity
* No additional parameters needed - automatically uses the system-assigned identity
*/
type SystemAssignedConfig = ManagedIdentityConfiguration;Usage Example:
// System-assigned managed identity (simplest configuration)
const mia = new ManagedIdentityApplication({});
// Acquire token for Microsoft Graph
const graphToken = await mia.acquireToken({
resource: "https://graph.microsoft.com/"
});
// Acquire token for Azure Resource Manager
const armToken = await mia.acquireToken({
resource: "https://management.azure.com/"
});
// Acquire token for Key Vault
const keyVaultToken = await mia.acquireToken({
resource: "https://vault.azure.net/"
});Configuration for using a specific user-assigned managed identity.
/**
* Configuration for user-assigned managed identity
* Specify identity using one of: clientId, resourceId, or objectId
*/
type UserAssignedConfig = {
managedIdentityIdParams: ManagedIdentityIdParams;
system?: NodeSystemOptions;
};Usage Examples:
// User-assigned managed identity by client ID
const miaByClientId = new ManagedIdentityApplication({
managedIdentityIdParams: {
userAssignedClientId: "12345678-1234-1234-1234-123456789012"
}
});
// User-assigned managed identity by resource ID
const miaByResourceId = new ManagedIdentityApplication({
managedIdentityIdParams: {
userAssignedResourceId: "/subscriptions/sub-id/resourceGroups/rg-name/providers/Microsoft.ManagedIdentity/userAssignedIdentities/identity-name"
}
});
// User-assigned managed identity by object ID
const miaByObjectId = new ManagedIdentityApplication({
managedIdentityIdParams: {
userAssignedObjectId: "87654321-4321-4321-4321-210987654321"
}
});
const tokenRequest = {
resource: "https://graph.microsoft.com/"
};
const response = await miaByClientId.acquireToken(tokenRequest);Managed Identity automatically detects and works with various Azure services:
/**
* Managed Identity source names (for reference)
* These are automatically detected - no manual configuration needed
*/
const ManagedIdentitySourceNames = {
/** Azure Instance Metadata Service (VMs, VMSS) */
IMDS: "IMDS",
/** Azure App Service and Function Apps */
APP_SERVICE: "APP_SERVICE",
/** Azure Arc enabled servers */
AZURE_ARC: "AZURE_ARC",
/** Azure Cloud Shell */
CLOUD_SHELL: "CLOUD_SHELL",
/** Azure Service Fabric */
SERVICE_FABRIC: "SERVICE_FABRIC",
/** Azure Machine Learning */
MACHINE_LEARNING: "MACHINE_LEARNING",
/** Default fallback to IMDS */
DEFAULT_TO_IMDS: "DEFAULT_TO_IMDS"
} as const;Supported Azure Services:
/**
* Request with cache control options
*/
type ManagedIdentityRequestWithCaching = {
/** Target resource URI for the token */
resource: string;
/** Force refresh instead of using cached token */
forceRefresh?: boolean;
/** Claims for conditional access scenarios */
claims?: string;
};Usage Example:
const mia = new ManagedIdentityApplication({});
// Use cached token if available and valid
const cachedResponse = await mia.acquireToken({
resource: "https://graph.microsoft.com/",
forceRefresh: false
});
// Force refresh from managed identity endpoint
const freshResponse = await mia.acquireToken({
resource: "https://graph.microsoft.com/",
forceRefresh: true
});
// With conditional access claims
const claimsResponse = await mia.acquireToken({
resource: "https://graph.microsoft.com/",
claims: JSON.stringify({
"access_token": {
"acrs": {
"essential": true,
"values": ["urn:microsoft:req1"]
}
}
})
});/**
* Managed Identity specific error class
*/
class ManagedIdentityError extends AuthError {
constructor(errorCode: string, errorMessage: string);
}
/**
* Common managed identity error codes
*/
const ManagedIdentityErrorCodes = {
/** Network request failed */
NETWORK_REQUEST_FAILED: "network_request_failed",
/** Invalid resource format */
INVALID_RESOURCE: "invalid_resource",
/** Managed identity not available on current platform */
PLATFORM_NOT_SUPPORTED: "platform_not_supported",
/** Environment variables malformed */
MALFORMED_ENVIRONMENT_VARIABLE: "malformed_environment_variable",
/** Timeout waiting for response */
REQUEST_TIMEOUT: "request_timeout",
/** File system access error */
FILE_NOT_FOUND: "file_not_found"
} as const;Usage Example:
import { ManagedIdentityError } from "@azure/msal-node";
try {
const response = await mia.acquireToken({
resource: "https://graph.microsoft.com/"
});
} catch (error) {
if (error instanceof ManagedIdentityError) {
switch (error.errorCode) {
case "platform_not_supported":
console.error("Managed Identity not supported on this platform");
break;
case "network_request_failed":
console.error("Network error accessing managed identity endpoint");
break;
case "invalid_resource":
console.error("Invalid resource URI provided");
break;
default:
console.error("Managed Identity error:", error.message);
}
} else {
console.error("Unexpected error:", error);
}
}/**
* Advanced managed identity configuration with system options
*/
type AdvancedManagedIdentityConfiguration = {
/** Client capabilities for conditional access */
clientCapabilities?: Array<string>;
/** User-assigned identity parameters */
managedIdentityIdParams?: ManagedIdentityIdParams;
/** System configuration */
system?: {
/** Logger configuration */
loggerOptions?: LoggerOptions;
/** Custom network client */
networkClient?: INetworkModule;
/** Proxy URL for network requests */
proxyUrl?: string;
/** Custom HTTP agent options */
customAgentOptions?: http.AgentOptions | https.AgentOptions;
/** Disable internal request retries */
disableInternalRetries?: boolean;
};
};Usage Example:
import { ManagedIdentityApplication, LogLevel } from "@azure/msal-node";
const mia = new ManagedIdentityApplication({
managedIdentityIdParams: {
userAssignedClientId: "12345678-1234-1234-1234-123456789012"
},
clientCapabilities: ["CP1"], // Conditional access capability
system: {
loggerOptions: {
loggerCallback: (level, message, containsPii) => {
if (!containsPii) {
console.log(`[${level}] ${message}`);
}
},
logLevel: LogLevel.Verbose,
piiLoggingEnabled: false
},
proxyUrl: "http://proxy.company.com:8080",
disableInternalRetries: false
}
});
const response = await mia.acquireToken({
resource: "https://graph.microsoft.com/",
claims: JSON.stringify({
"access_token": {
"xms_cc": {
"values": ["CP1"]
}
}
})
});const mia = new ManagedIdentityApplication({});
const graphToken = await mia.acquireToken({
resource: "https://graph.microsoft.com/"
});
// Use token to call Microsoft Graph
const response = await fetch("https://graph.microsoft.com/v1.0/me", {
headers: {
"Authorization": `Bearer ${graphToken.accessToken}`
}
});const armToken = await mia.acquireToken({
resource: "https://management.azure.com/"
});
// Use token for Azure Resource Manager APIs
const subscriptions = await fetch("https://management.azure.com/subscriptions?api-version=2020-01-01", {
headers: {
"Authorization": `Bearer ${armToken.accessToken}`
}
});const keyVaultToken = await mia.acquireToken({
resource: "https://vault.azure.net/"
});
// Use token for Key Vault operations
const secret = await fetch("https://my-vault.vault.azure.net/secrets/my-secret?api-version=7.2", {
headers: {
"Authorization": `Bearer ${keyVaultToken.accessToken}`
}
});const storageToken = await mia.acquireToken({
resource: "https://storage.azure.com/"
});
// Use token for Azure Storage operations
const blobs = await fetch("https://myaccount.blob.core.windows.net/mycontainer?restype=container&comp=list", {
headers: {
"Authorization": `Bearer ${storageToken.accessToken}`,
"x-ms-version": "2020-04-08"
}
});