Microsoft Authentication Library for JavaScript
repository·dev·Indexed 26 days ago
https://github.com/azuread/microsoft-authentication-library-for-jsMSAL.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.
What's inside MSAL.js
- 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.
Overview of @azure/msal-browser
devThe
@azure/msal-browserpackage 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.
Overview of MSAL Angular
devMSAL 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-browserpackage. - 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-angulardoes NOT support the implicit flow. For implicit flow support, you must use the legacy MSAL Angular v1 library.
- It wraps the
Understand Resources and Scopes in MSAL.js
devMSAL.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
scp1cannot be used for Resource A withscp2, nor can it be used for Resource B. The recipient is validated via theaud(audience) claim, and permissions are validated via thescp(scope) claim.MSAL React Sample Implementation Details
devThe sample demonstrates several key MSAL React patterns:
MsalProvider: Wraps the application in./src/App.jsto provide context, hooks, and components to all children.PublicClientApplicationInitialization: Performed in./src/index.jsand passed to the provider.- Conditional Rendering: Uses
AuthenticatedTemplateandUnauthenticatedTemplate(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 thePublicClientApplicationinstance to invokeloginorlogoutfunctions.
- Custom Navigation: Implements
INavigationClientin./src/utils/NavigationClient.jsto override default MSAL.js navigation behavior.
MSAL.js Next.js Sample Implementation Details
devThe sample demonstrates several key MSAL.js patterns for React/Next.js applications:
- Context Provider:
./pages/_app.jsimplementsMsalProvider, allowing all child components to access@azure/msal-reactcontext, hooks, and components. - Conditional Rendering:
./pages/index.jsusesAuthenticatedTemplateandUnauthenticatedTemplateto show different content based on the user's sign-in state. - Protected Routes:
./pages/profile.jsusesMsalAuthenticationTemplateto 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.jsxto conditionally render Sign In or Sign Out buttons.useMsal: Used in./src/ui-components/SignInButton.jsxand./src/ui-components/SignOutButton.jsxto access thePublicClientApplicationinstance and invokeloginorlogoutfunctions.
- Configuration:
./src/authConfig.jscontains thePublicClientApplicationconfiguration and token request parameters. - API Integration:
./src/utils/MsGraphApiCall.jsdemonstrates making calls to the MS Graph API using an acquired access token. - Custom Navigation:
./src/utils/NavigationClient.jsshows an implementation ofINavigationClientto override default MSAL.js navigation behavior.
- Context Provider:
Supported Application Scenarios
devMSAL Node is designed to support the following application scenarios:
- Desktop app that calls web APIs
- Web app that calls web APIs
- Web APIs that call web APIs
- Daemon apps
Implement On-Behalf-Of (OBO) flow with distributed Redis caching in MSAL Node
devThis 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 andnode-redisto persist tokens.Understand the Authority parameter in MSAL
devThe
authorityparameter 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:
Endpoint Path Segment Description 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. Understand Multi-tenant Accounts and Tenant Profiles
devMSAL supports acquiring and caching tokens across multiple tenants using multi-tenant accounts.
- Multi-tenant Accounts: These are
AccountInfoobjects that contain tenant-specific data and aMap<string, TenantProfile>calledtenantProfiles. The keys in this map are tenant IDs, and the values are the correspondingTenantProfileobjects. - Tenant Profiles: A
TenantProfileis a subset ofAccountInfoproperties 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.
- Multi-tenant Accounts: These are
Understand MSAL Log Decoder output and features
devOutput Behavior
The script saves the decoded logs to a new file in the same directory as the input file, appending a
-decodedsuffix before the extension.- Example:
/path/to/debug.logbecomes/path/to/debug-decoded.log
Key Features
- Automatic Version Detection: Fetches mappings based on the
module@versionfound 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.
- Example:
MSAL React Sample Implementation Overview
devThis sample demonstrates how to integrate
@azure/msal-reactwith React 18 and MUI v5. Key implementation patterns include:- Initialization: Initializing
PublicClientApplicationinindex.jsxand providing it viaMsalProviderinApp.jsx. - Conditional Rendering: Using
AuthenticatedTemplateandUnauthenticatedTemplateto show/hide UI based on auth state. - Protected Routes: Using
MsalAuthenticationTemplateto automatically trigger sign-in for specific routes. - Hooks Usage:
useIsAuthenticated: To conditionally render Sign In/Sign Out buttons.useMsal: To access thePublicClientApplicationinstance for calling.loginPopup(),.loginRedirect(), or.logout().
- API Integration: Using access tokens acquired via MSAL to call services like the MS Graph API.
- Initialization: Initializing