or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

authentication-flows.mdconfidential-client.mdconfiguration.mderror-handling.mdindex.mdmanaged-identity.mdpublic-client.mdtoken-cache.md
tile.json

tessl/npm-azure--msal-node

Microsoft Authentication Library for Node - A comprehensive Node.js authentication library for Microsoft identity platform supporting multiple OAuth 2.0 flows

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@azure/msal-node@3.7.x

To install, run

npx @tessl/cli install tessl/npm-azure--msal-node@3.7.0

index.mddocs/

MSAL Node

Microsoft Authentication Library for Node (MSAL Node) is a comprehensive TypeScript library that enables Node.js applications to authenticate users and acquire tokens using the Microsoft Identity platform. It supports multiple OAuth 2.0 authentication flows for both public and confidential client applications, enabling authentication with Azure AD work and school accounts, Microsoft personal accounts, and social identity providers through Azure AD B2C.

Package Information

  • Package Name: @azure/msal-node
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @azure/msal-node

Core Imports

import { 
  PublicClientApplication, 
  ConfidentialClientApplication,
  ManagedIdentityApplication,
  type Configuration,
  type AuthenticationResult
} from "@azure/msal-node";

For CommonJS:

const { 
  PublicClientApplication, 
  ConfidentialClientApplication,
  ManagedIdentityApplication
} = require("@azure/msal-node");

Basic Usage

Public Client (Desktop/Mobile Apps)

import { PublicClientApplication } from "@azure/msal-node";

const pca = new PublicClientApplication({
  auth: {
    clientId: "your-client-id",
    authority: "https://login.microsoftonline.com/common"
  }
});

// Authorization code flow
const authCodeUrlParameters = {
  scopes: ["user.read"],
  redirectUri: "http://localhost:3000/redirect"
};

const authUrl = await pca.getAuthCodeUrl(authCodeUrlParameters);
// Redirect user to authUrl, get code from callback

const tokenRequest = {
  code: "authorization-code-from-callback",
  scopes: ["user.read"],
  redirectUri: "http://localhost:3000/redirect"
};

const response = await pca.acquireTokenByCode(tokenRequest);
console.log(response.accessToken);

Confidential Client (Server Applications)

import { ConfidentialClientApplication } from "@azure/msal-node";

const cca = new ConfidentialClientApplication({
  auth: {
    clientId: "your-client-id",
    clientSecret: "your-client-secret",
    authority: "https://login.microsoftonline.com/your-tenant-id"
  }
});

// Client credentials flow
const clientCredentialRequest = {
  scopes: ["https://graph.microsoft.com/.default"]
};

const response = await cca.acquireTokenByClientCredential(clientCredentialRequest);
console.log(response.accessToken);

Managed Identity (Azure Resources)

import { ManagedIdentityApplication } from "@azure/msal-node";

const mia = new ManagedIdentityApplication({});

const tokenRequest = {
  resource: "https://graph.microsoft.com/"
};

const response = await mia.acquireToken(tokenRequest);
console.log(response.accessToken);

Architecture

MSAL Node is built around several key components:

  • Client Applications: Different application types (Public, Confidential, Managed Identity) providing specialized authentication flows
  • Request/Response System: Strongly-typed request objects for each OAuth 2.0 flow with comprehensive response handling
  • Token Cache: In-memory and distributed cache system for storing tokens with serialization support
  • Configuration System: Hierarchical configuration with authentication, system, cache, and telemetry options
  • Error Handling: Comprehensive error classes with specific error codes for different scenarios
  • Cryptographic Provider: Secure cryptographic operations including PKCE, JWT signatures, and certificate handling

Capabilities

Public Client Applications

Core functionality for applications that cannot securely store client secrets, including desktop apps, mobile apps, and single-page applications.

interface IPublicClientApplication {
  getAuthCodeUrl(request: AuthorizationUrlRequest): Promise<string>;
  acquireTokenByCode(request: AuthorizationCodeRequest): Promise<AuthenticationResult>;
  acquireTokenInteractive(request: InteractiveRequest): Promise<AuthenticationResult>;
  acquireTokenSilent(request: SilentFlowRequest): Promise<AuthenticationResult>;
  acquireTokenByRefreshToken(request: RefreshTokenRequest): Promise<AuthenticationResult | null>;
  acquireTokenByDeviceCode(request: DeviceCodeRequest): Promise<AuthenticationResult | null>;
  acquireTokenByUsernamePassword(request: UsernamePasswordRequest): Promise<AuthenticationResult | null>;
  getTokenCache(): TokenCache;
  getLogger(): Logger;
  setLogger(logger: Logger): void;
  clearCache(): void;
  getAllAccounts(): Promise<AccountInfo[]>;
  signOut(request: SignOutRequest): Promise<void>;
}

class PublicClientApplication implements IPublicClientApplication {
  constructor(configuration: Configuration);
}

Public Client Applications

Confidential Client Applications

Advanced functionality for applications that can securely store client secrets, including server applications, web APIs, and daemon applications.

interface IConfidentialClientApplication {
  getAuthCodeUrl(request: AuthorizationUrlRequest): Promise<string>;
  acquireTokenByCode(request: AuthorizationCodeRequest): Promise<AuthenticationResult>;
  acquireTokenSilent(request: SilentFlowRequest): Promise<AuthenticationResult | null>;
  acquireTokenByRefreshToken(request: RefreshTokenRequest): Promise<AuthenticationResult | null>;
  acquireTokenByClientCredential(request: ClientCredentialRequest): Promise<AuthenticationResult | null>;
  acquireTokenOnBehalfOf(request: OnBehalfOfRequest): Promise<AuthenticationResult | null>;
  acquireTokenByUsernamePassword(request: UsernamePasswordRequest): Promise<AuthenticationResult | null>;
  getTokenCache(): TokenCache;
  getLogger(): Logger;
  setLogger(logger: Logger): void;
  clearCache(): void;
  SetAppTokenProvider(provider: IAppTokenProvider): void;
}

class ConfidentialClientApplication implements IConfidentialClientApplication {
  constructor(configuration: Configuration);
}

Confidential Client Applications

Managed Identity Applications

Azure Managed Identity authentication for applications running on Azure resources like VMs, App Service, and Function Apps.

class ManagedIdentityApplication {
  constructor(configuration?: ManagedIdentityConfiguration);
  acquireToken(request: ManagedIdentityRequestParams): Promise<AuthenticationResult | null>;
  getManagedIdentitySource(): ManagedIdentitySourceNames;
}

type ManagedIdentityConfiguration = {
  clientCapabilities?: Array<string>;
  managedIdentityIdParams?: ManagedIdentityIdParams;
  system?: NodeSystemOptions;
};

type ManagedIdentityIdParams = {
  userAssignedClientId?: string;
  userAssignedResourceId?: string;
  userAssignedObjectId?: string;
};

Managed Identity Applications

Authentication Flows

Complete set of OAuth 2.0 authentication flows with strongly-typed request objects and comprehensive configuration options.

type AuthorizationUrlRequest = {
  scopes: string[];
  redirectUri: string;
  prompt?: PromptValue;
  account?: AccountInfo;
  loginHint?: string;
  domainHint?: string;
  extraQueryParameters?: Record<string, string>;
};

type AuthorizationCodeRequest = {
  scopes: string[];
  redirectUri: string;
  code: string;
  state?: string;
  authority?: string;
  correlationId?: string;
  claims?: string;
};

type ClientCredentialRequest = {
  scopes: string[];
  authority?: string;
  clientAssertion?: string | (() => string);
  skipCache?: boolean;
};

Authentication Flows

Token Cache Management

Comprehensive token caching system with in-memory storage, serialization support, and distributed cache capabilities.

interface ITokenCache {
  getAllAccounts(): Promise<AccountInfo[]>;
  getAccountByHomeId(homeAccountId: string): Promise<AccountInfo | null>;
  getAccountByLocalId(localAccountId: string): Promise<AccountInfo | null>;
  removeAccount(account: AccountInfo): Promise<void>;
}

class TokenCache implements ITokenCache, ISerializableTokenCache {
  // Cache management methods
}

type CacheOptions = {
  cachePlugin?: ICachePlugin;
  claimsBasedCachingEnabled?: boolean;
};

Token Cache Management

Configuration System

Hierarchical configuration system supporting authentication options, system settings, cache configuration, and telemetry.

type Configuration = {
  auth: NodeAuthOptions;
  broker?: BrokerOptions;
  cache?: CacheOptions;
  system?: NodeSystemOptions;
  telemetry?: NodeTelemetryOptions;
};

type NodeAuthOptions = {
  clientId: string;
  authority?: string;
  clientSecret?: string;
  clientAssertion?: string | ClientAssertionCallback;
  clientCertificate?: {
    thumbprintSha256?: string;
    privateKey: string;
    x5c?: string;
  };
  knownAuthorities?: Array<string>;
  protocolMode?: ProtocolMode;
};

Configuration System

Error Handling

Comprehensive error handling with specific error classes and detailed error codes for different authentication scenarios.

class NodeAuthError extends AuthError {
  static createStateNotFoundError(): NodeAuthError;
  static createLoopbackServerTimeoutError(): NodeAuthError;
}

class ManagedIdentityError extends AuthError {
  // Managed Identity specific errors
}

type AuthErrorCodes = {
  unexpectedError: string;
  postRequestFailed: string;
  getRequestFailed: string;
  // Additional error codes...
};

Error Handling

Specialized Client Classes

Low-level client classes for specific OAuth 2.0 flows, providing direct access to individual authentication methods.

/**
 * OAuth 2.0 client credential flow client
 */
class ClientCredentialClient extends BaseClient {
  constructor(configuration: ClientConfiguration, appTokenProvider?: IAppTokenProvider);
  acquireToken(request: CommonClientCredentialRequest): Promise<AuthenticationResult | null>;
}

/**
 * OAuth 2.0 device code flow client
 */
class DeviceCodeClient extends BaseClient {
  constructor(configuration: ClientConfiguration);
  acquireToken(request: CommonDeviceCodeRequest): Promise<AuthenticationResult | null>;
}

/**
 * OAuth 2.0 on-behalf-of flow client
 */
class OnBehalfOfClient extends BaseClient {
  constructor(configuration: ClientConfiguration);
  acquireToken(request: CommonOnBehalfOfRequest): Promise<AuthenticationResult | null>;
}

/**
 * OAuth 2.0 username/password flow client
 */
class UsernamePasswordClient extends BaseClient {
  constructor(configuration: ClientConfiguration);
  acquireToken(request: CommonUsernamePasswordRequest): Promise<AuthenticationResult | null>;
}

/**
 * Base client application class
 */
abstract class ClientApplication {
  protected constructor(configuration: Configuration);
  getTokenCache(): TokenCache;
  getLogger(): Logger;
  setLogger(logger: Logger): void;
  clearCache(): void;
}

Cryptographic Provider

Cryptographic operations for authentication flows including PKCE, JWT signatures, and certificate handling.

/**
 * Cryptographic provider for Node.js environments
 */
class CryptoProvider {
  /** Generate UUID v4 */
  createNewGuid(): string;
  /** Generate PKCE code verifier */
  generatePkceCodes(): PkceCodes;
  /** Generate SHA256 hash */
  sha256Digest(inputString: string): Promise<string>;
  /** Sign JWT with private key */
  signJwt(payload: object, privateKey: string): Promise<string>;
  /** Verify JWT signature */
  verifyJwt(token: string, publicKey: string): Promise<object>;
}

type PkceCodes = {
  verifier: string;
  challenge: string;
};

Client Assertion

Certificate-based authentication support for confidential client applications.

/**
 * Client assertion for certificate-based authentication
 */
class ClientAssertion {
  constructor(assertion: string);
  getJwt(): string;
  static fromCertificate(privateKey: string, thumbprint: string, audience: string): ClientAssertion;
}

Common Types

Authentication Results

type AuthenticationResult = {
  authority: string;
  uniqueId: string;
  tenantId: string;
  scopes: string[];
  account: AccountInfo | null;
  idToken: string;
  idTokenClaims: IdTokenClaims;
  accessToken: string;
  fromCache: boolean;
  expiresOn: Date | null;
  correlationId: string;
  requestId?: string;
};

type AccountInfo = {
  homeAccountId: string;
  environment: string;
  tenantId: string;
  username: string;
  localAccountId: string;
  name?: string;
  idTokenClaims?: IdTokenClaims;
};

Protocol Types

enum PromptValue {
  LOGIN = "login",
  SELECT_ACCOUNT = "select_account",
  CONSENT = "consent",
  NONE = "none"
}

enum ResponseMode {
  QUERY = "query",
  FRAGMENT = "fragment",
  FORM_POST = "form_post"
}

enum ProtocolMode {
  AAD = "AAD",
  OIDC = "OIDC"
}

enum AzureCloudInstance {
  None = "",
  AzurePublic = "https://login.microsoftonline.com",
  AzurePpope = "https://login.microsoftonline.us",
  AzureChina = "https://login.chinacloudapi.cn",
  AzureGermany = "https://login.microsoftonline.de"
}

type ClientAssertionCallback = () => string;

const ManagedIdentitySourceNames = {
  IMDS: "IMDS",
  APP_SERVICE: "APP_SERVICE",
  AZURE_ARC: "AZURE_ARC",
  CLOUD_SHELL: "CLOUD_SHELL",
  SERVICE_FABRIC: "SERVICE_FABRIC",
  MACHINE_LEARNING: "MACHINE_LEARNING",
  DEFAULT_TO_IMDS: "DEFAULT_TO_IMDS"
} as const;

type ManagedIdentitySourceNames = typeof ManagedIdentitySourceNames[keyof typeof ManagedIdentitySourceNames];