What is @azure/msal-node?
The @azure/msal-node package is a Microsoft library that enables Node.js applications to authenticate users and access secured resources in the Microsoft identity platform, such as Microsoft 365, Azure, and other resources that rely on Microsoft accounts. It supports various OAuth 2.0 and OpenID Connect flows.
What are @azure/msal-node's main functionalities?
Authentication
This code sample demonstrates how to configure the MSAL client and get an authorization code URL, which is the first step in the OAuth 2.0 authorization code flow.
const msal = require('@azure/msal-node');
const config = {
auth: {
clientId: 'your_client_id',
authority: 'https://login.microsoftonline.com/common',
clientSecret: 'your_client_secret',
}
};
const cca = new msal.ConfidentialClientApplication(config);
const authCodeUrlParameters = {
scopes: ['user.read'],
redirectUri: 'http://localhost:3000/redirect',
};
cca.getAuthCodeUrl(authCodeUrlParameters).then((response) => {
console.log(response);
});
Acquiring Tokens
This code sample shows how to exchange an authorization code for an access token, which can be used to access secured resources.
const tokenRequest = {
code: 'authorization_code_received_from_auth_code_url',
scopes: ['user.read'],
redirectUri: 'http://localhost:3000/redirect',
};
cca.acquireTokenByCode(tokenRequest).then((response) => {
console.log(response);
}).catch((error) => {
console.error(error);
});
Silent Token Acquisition
This code sample illustrates how to silently acquire an access token using a cached account, which is useful for renewing tokens without user interaction.
const silentTokenRequest = {
account: cca.getAccountByHomeId('user_home_id'),
scopes: ['user.read'],
};
cca.acquireTokenSilent(silentTokenRequest).then((response) => {
console.log(response);
}).catch((error) => {
if (error instanceof msal.InteractionRequiredAuthError) {
// Fallback to interactive method if silent acquisition fails
}
});
Other packages similar to @azure/msal-node
passport-azure-ad
Passport-azure-ad is a collection of Passport Strategies to help you integrate with Azure Active Directory. It is similar to @azure/msal-node but uses the Passport.js framework, which is popular for handling authentication in Node.js applications.
oidc-client
The oidc-client package provides a client-side library for web applications that need to perform OpenID Connect (OIDC) and OAuth 2.0 protocols. Unlike @azure/msal-node, which is designed for server-side Node.js applications, oidc-client is intended for use in browser-based applications.
simple-oauth2
Simple-oauth2 is a Node.js library for interacting with OAuth 2.0 and simplifying the process of adding token-based authentication to applications. It provides a simpler and more lightweight alternative to @azure/msal-node, but it does not have specific integrations with Microsoft identity platform.
Microsoft Authentication Library for Node (msal-node)
- About
- FAQ
- Changelog
- Prerequisites
- Installation
- Node Version Support
- Usage
- Samples
- Build Library
- Security Reporting
- License
- Code of Conduct
About
MSAL Node enables applications to authenticate users using Azure AD work and school accounts (AAD), Microsoft personal accounts (MSA) and social identity providers like Facebook, Google, LinkedIn, Microsoft accounts, etc. through Azure AD B2C service. It also enables your app to get tokens to access Microsoft Cloud services such as Microsoft Graph.
OAuth2.0 grant types supported:
The current version supports the following ways of acquiring tokens:
Public Client:
Confidential Client:
[Coming Soon] In the future we plan to add support for:
More details on different grant types supported by Microsoft authentication libraries in general can be found here.
Scenarios supported:
The scenarios supported with this library are:
- Desktop app that calls web APIs
- Web app that calls web APIs
- Web APIs that call web APIs
- Daemon apps
More details on scenarios and the authentication flows that map to each of them can be found here.
FAQ
See here.
Prerequisites
Before using @azure/msal-node
you will need to register your app in the azure portal:
Installation
Via NPM:
npm install @azure/msal-node
Node Version Support
MSAL Node will follow the Long Term Support (LTS) schedule of the Node.js project. Our support plan is as follows.
Any major MSAL Node release:
- Will support stable (even-numbered) Maintenance LTS, Active LTS, and Current versions of Node
- Will drop support for any previously supported Node versions that have reached end of life
- Will not support prerelease/preview/pending versions until they are stable
MSAL Node version | MSAL support status | Supported Node versions |
---|
1.x.x | Active development | 10, 12, 14, 16, 18 |
Usage
MSAL basics
Samples
There are multiple samples included in the repository that use MSAL Node to acquire tokens. These samples are currently used for manual testing, and are not meant to be a reference of best practices, therefore use judgement and do not blindly copy this code to any production applications.
AAD samples:
- auth-code: Express app using OAuth2.0 authorization code flow.
- auth-code-pkce: Express app using OAuth2.0 authorization code flow with PKCE.
- device-code: Command line app using OAuth 2.0 device code flow.
- refresh-token: Command line app using OAuth 2.0 refresh flow.
- silent-flow: Express app using OAuth2.0 authorization code flow to acquire a token and store in the token cache, and silent flow to use tokens in the token cache.
- client-credentials: Daemon app using OAuth 2.0 client credential grant to acquire a token.
- on-behalf-of: Web application using OAuth 2.0 auth code flow to acquire a token for a web API. The web API validates the token, and calls Microsoft Graph on behalf of the user who authenticated in the web application.
- username-password: Web application using OAuth 2.0 resource owner password credentials (ROPC) flow to acquire a token for a web API.
- ElectronTestApp: Electron desktop application using OAuth 2.0 auth code with PKCE flow to acquire a token for a web API such as Microsoft Graph.
- ExpressTestApp: Express.js MVC web application using OAuth 2.0 auth code with PKCE flow to acquire a token for a web API such as Microsoft Graph.
- Hybrid Spa Sample: Sample demonstrating how to use
enableSpaAuthorizationCode
to perform SSO for applications that leverage server-side and client-side authentication using MSAL Browser and MSAL Node.
B2C samples:
- b2c-auth-code: Express app using OAuth2.0 authorization code flow.
- b2c-auth-code-pkce: Express app using OAuth2.0 authorization code flow with PKCE.
- b2c-silent-flow: Express app using OAuth2.0 authorization code flow to acquire a token and store in the token cache, and silent flow to use tokens in the token cache.
- ms-identity-b2c-javascript-nodejs-management: Command line app using OAuth 2.0 client credentials flow for performing user management operations on an Azure AD / Azure AD B2C tenant
Others:
Build and Test
- If you don't have lerna installed, run
npm install -g lerna
- Run
lerna bootstrap
from anywhere within microsoft-authentication-library-for-js.git
. - Navigate to
microsoft-authentication-library-for-js/lib/msal-common
and run npm run build
- Navigate to
microsoft-authentication-library-for-js/lib/msal-node
and run npm run build
lerna bootstrap
cd lib/msal-common/
npm run build
cd lib/msal-node/
npm run build
Local Development
Below is a list of commands you will probably find useful:
npm run build:modules:watch
Runs the project in development/watch mode. Your project will be rebuilt upon changes. TSDX has a special logger for you convenience. Error messages are pretty printed and formatted for compatibility VS Code's Problems tab. The library will be rebuilt if you make edits.
npm run build
Bundles the package to the dist
folder.
The package is optimized and bundled with Rollup into multiple formats (CommonJS, UMD, and ES Module).
lerna bootstrap
If you are running the project in development/watch mode, or have made changes in msal-common
and need them reflecting across the project, please run lerna bootstrap
to link all the symbols. Please note that npm install
will unlink all the code, hence it is advised to run lerna bootstrap
post installation.
npm run lint
Runs eslint with Prettier
npm test
, npm run test:coverage
, npm run test:watch
Runs the test watcher (Jest) in an interactive mode.
By default, runs tests related to files changed since the last commit.
Generate code coverage by adding the flag --coverage. No additional setup needed. Jest can collect code coverage information from entire projects, including untested files.
Security Reporting
If you find a security issue with our libraries or services please report it to secure@microsoft.com with as much detail as possible. Your submission may be eligible for a bounty through the Microsoft Bounty program. Please do not post security issues to GitHub Issues or any other public site. We will contact you shortly upon receiving the information. We encourage you to get notifications of when security incidents occur by visiting this page and subscribing to Security Advisory Alerts.
License
Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License.
We Value and Adhere to the Microsoft Open Source Code of Conduct
This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.