Microsoft Authentication Library for JavaScript

repository·dev·Indexed 26 days ago

https://github.com/azuread/microsoft-authentication-library-for-js

MSAL.js provides authentication and token acquisition capabilities for browser-based and Node.js applications using Microsoft Identity platforms. It includes packages such as @azure/msal-browser for SPAs, @azure/msal-angular for Angular applications using OAuth 2.0 Authorization Code Flow with PKCE, and @azure/msal-node-extensions for advanced Node.js features like cross-platform cache persistence and native token brokering.

Tokens
203.9K
Snippets
418
Records
870
Agent score
87%

What's inside MSAL.js

  1. Overview of Microsoft Authentication Library for JavaScript (MSAL.js)

    dev
    MSAL.js enables client-side and server-side JavaScript applications to authenticate users using Microsoft Entra ID (for work and school accounts), Microsoft personal accounts (MSA), and social identity providers (Facebook, Google, LinkedIn, etc.) via Azure AD B2C. It also provides tokens to access Microsoft Cloud services like Microsoft Graph.
  2. Overview of @azure/msal-browser

    dev

    The @azure/msal-browser package enables client-side JavaScript applications to authenticate users using:

    • Microsoft Entra ID (Work and school accounts)
    • Microsoft personal accounts (MSA)
    • Social identity providers (Facebook, Google, LinkedIn, etc.) via Azure AD B2C

    It allows your application to acquire tokens to access Microsoft Cloud services like Microsoft Graph. This library uses the OAuth 2.0 Authorization Code Flow with PKCE and does NOT support the implicit flow.

  3. Overview of MSAL Angular

    dev

    MSAL Angular enables Angular web applications to authenticate users using Azure AD (AAD) work and school accounts, Microsoft personal accounts (MSA), and social identity providers (e.g., Facebook, Google, LinkedIn) via Azure AD B2C. It also facilitates obtaining tokens to access Microsoft Cloud services like Microsoft Graph.

    Key technical details:

    • It wraps the @azure/msal-browser package.
    • It uses the OAuth 2.0 Authorization Code Flow with PKCE.
    • It is designed for Angular Web Applications without backend servers.
    • Note: The current version of @azure/msal-angular does NOT support the implicit flow. For implicit flow support, you must use the legacy MSAL Angular v1 library.
  4. Understand Resources and Scopes in MSAL.js

    dev

    MSAL.js uses a scope-centric model for accessing resources.

    • Resource: Any application that can receive an Access Token (e.g., MS Graph API or your own web API).
    • Scope (Permission): An aspect of a resource that an Access Token grants rights to.

    Crucial Rule: Access Token requests are per-resource-per-scope(s). An Access Token requested for Resource A with scope scp1 cannot be used for Resource A with scp2, nor can it be used for Resource B. The recipient is validated via the aud (audience) claim, and permissions are validated via the scp (scope) claim.

  5. MSAL React Sample Implementation Details

    dev

    The sample demonstrates several key MSAL React patterns:

    • MsalProvider: Wraps the application in ./src/App.js to provide context, hooks, and components to all children.
    • PublicClientApplication Initialization: Performed in ./src/index.js and passed to the provider.
    • Conditional Rendering: Uses AuthenticatedTemplate and UnauthenticatedTemplate (e.g., in ./src/pages/Home.jsx) to show different content based on auth state.
    • Protected Routes: Uses MsalAuthenticationTemplate (e.g., in ./src/pages/Profile.jsx) to automatically trigger sign-in for unauthenticated users.
    • Hooks:
      • useIsAuthenticated: Used to conditionally render UI elements like Sign In/Sign Out buttons.
      • useMsal: Used to access the PublicClientApplication instance to invoke login or logout functions.
    • Custom Navigation: Implements INavigationClient in ./src/utils/NavigationClient.js to override default MSAL.js navigation behavior.
  6. MSAL.js Next.js Sample Implementation Details

    dev

    The sample demonstrates several key MSAL.js patterns for React/Next.js applications:

    • Context Provider: ./pages/_app.js implements MsalProvider, allowing all child components to access @azure/msal-react context, hooks, and components.
    • Conditional Rendering: ./pages/index.js uses AuthenticatedTemplate and UnauthenticatedTemplate to show different content based on the user's sign-in state.
    • Protected Routes: ./pages/profile.js uses MsalAuthenticationTemplate to protect a route. It automatically invokes sign-in if the user is unauthenticated and acquires an access token to call MS Graph if they are authenticated.
    • Hooks Usage:
      • useIsAuthenticated: Used in ./src/ui-components/SignInSignOutButton.jsx to conditionally render Sign In or Sign Out buttons.
      • useMsal: Used in ./src/ui-components/SignInButton.jsx and ./src/ui-components/SignOutButton.jsx to access the PublicClientApplication instance and invoke login or logout functions.
    • Configuration: ./src/authConfig.js contains the PublicClientApplication configuration and token request parameters.
    • API Integration: ./src/utils/MsGraphApiCall.js demonstrates making calls to the MS Graph API using an acquired access token.
    • Custom Navigation: ./src/utils/NavigationClient.js shows an implementation of INavigationClient to override default MSAL.js navigation behavior.
  7. Implement On-Behalf-Of (OBO) flow with distributed Redis caching in MSAL Node

    dev
    This sample demonstrates how to implement a confidential client application using MSAL Node that acts as a middle-tier Web API. The API uses the OAuth 2.0 On-Behalf-Of flow to call Microsoft Graph on behalf of a user. It also implements the distributed token caching pattern using a custom cache plugin with Redis and node-redis to persist tokens.
  8. Understand the Authority parameter in MSAL

    dev

    The authority parameter in MSAL configuration specifies the URL of the Identity Provider (IdP) or Security Token Service (STS) from which the application acquires tokens. MSAL uses this URL to perform endpoint discovery, gathering necessary metadata (like supported scopes and signing keys) to facilitate token requests.

    A standard authority URL follows this structure:

    https://<domain-of-the-service>/<tenant-identifier>

    MSAL uses the authority to locate three critical endpoints:

    EndpointPath SegmentDescription
    OpenID Configuration/.well-known/openid-configurationContains metadata required for token requests (scopes, claims, signing keys, etc.).
    Authorize/oauth2/v2.0/authorizeThe endpoint used to return an authorization code via the redirect URI, typically prompting user interaction.
    Token/oauth2/v2.0/tokenThe endpoint where the client app exchanges an authorization code for access and ID tokens via a POST request.
  9. Understand Multi-tenant Accounts and Tenant Profiles

    dev

    MSAL supports acquiring and caching tokens across multiple tenants using multi-tenant accounts.

    • Multi-tenant Accounts: These are AccountInfo objects that contain tenant-specific data and a Map<string, TenantProfile> called tenantProfiles. The keys in this map are tenant IDs, and the values are the corresponding TenantProfile objects.
    • Tenant Profiles: A TenantProfile is a subset of AccountInfo properties that vary by tenant, created from the claims in the ID token issued by each specific tenant.

    Important Constraints:

    • Access and ID tokens are tenant-specific.
    • Refresh Tokens are shared across tenants.
    • Linking: Tenant profiles only link if the user authenticates with the same account across different tenants. If a user uses different accounts for different tenants, they will be treated as completely separate accounts and will not be linked.
  10. Understand MSAL Log Decoder output and features

    dev

    Output Behavior

    The script saves the decoded logs to a new file in the same directory as the input file, appending a -decoded suffix before the extension.

    • Example: /path/to/debug.log becomes /path/to/debug-decoded.log

    Key Features

    • Automatic Version Detection: Fetches mappings based on the module@version found in the log.
    • Multi-Module & Version Support: Handles logs from multiple MSAL packages (e.g., msal-browser, msal-common) and multiple versions in one file.
    • Mapping Fetching: Automatically downloads mappings from the npm registry and caches them in temp/log-mappings/ for 24 hours.
    • Local Fallback: Uses local mapping files if remote fetching fails.
    • Non-MSAL Preservation: Lines that do not match the MSAL log pattern are left unchanged in the output.
  11. MSAL React Sample Implementation Overview

    dev

    This sample demonstrates how to integrate @azure/msal-react with React 18 and MUI v5. Key implementation patterns include:

    • Initialization: Initializing PublicClientApplication in index.jsx and providing it via MsalProvider in App.jsx.
    • Conditional Rendering: Using AuthenticatedTemplate and UnauthenticatedTemplate to show/hide UI based on auth state.
    • Protected Routes: Using MsalAuthenticationTemplate to automatically trigger sign-in for specific routes.
    • Hooks Usage:
      • useIsAuthenticated: To conditionally render Sign In/Sign Out buttons.
      • useMsal: To access the PublicClientApplication instance for calling .loginPopup(), .loginRedirect(), or .logout().
    • API Integration: Using access tokens acquired via MSAL to call services like the MS Graph API.