- Overview
- Scenario
- Contents
- Prerequisites
- Setup
- Registration
- Running the sample
- Explore the sample
- About the code
- More information
- Community Help and Support
- Contributing
This sample demonstrates a Node.js & Express web application calling a Node.js & Express web API protected by Azure AD using the Microsoft Authentication Library for Node.js (MSAL Node). In doing so, it illustrates authorization concepts such as OAuth 2.0 Authorization Code Grant, access token validation and more.
- The client application uses the MSAL Node to sign-in a user and obtain a JWT Access Token from Azure AD.
- The Access Token is used as a bearer token to authorize the user to access the resource.
- The resource owner responds with the resource that the user has access to.
| File/folder | Description |
|---|---|
AppCreationScripts/ |
Contains Powershell scripts to automate app registration. |
ReadmeFiles/ |
Contains images and diagrams for the README. |
WebApp/appSettings.json |
Contains authentication parameters for the web app. |
WebApp/cache.json |
Stores MSAL Node token cache. |
WebApp/App/app.js |
Web application entry point. |
WebApp/App/routes/router.js |
Router configuration where authentication middleware added. |
WebAPI/config.json |
Contains authentication parameters for the web API. |
WebAPI/index.js |
web API entry point. |
- Node.js must be installed to run this sample.
- Visual Studio Code is recommended for running and editing this sample.
- VS Code Azure Tools extension is recommended for interacting with Azure through VS Code Interface.
- A modern web browser. This sample uses ES6 conventions and will not run on Internet Explorer.
- An Azure AD tenant. For more information, see: How to get an Azure AD tenant
- A user account in your Azure AD tenant. This sample will not work with a personal Microsoft account. If you're signed in to the Azure portal with a personal Microsoft account and have not created a user account in your directory before, you will need to create one before proceeding.
From your shell or command line:
git clone https://github.com/Azure-Samples/ms-identity-javascript-nodejs-tutorial.gitor download and extract the repository .zip file.
⚠️ To avoid path length limitations on Windows, we recommend cloning into a directory near the root of your drive.
Locate the root of the sample folder. Then:
cd 3-Authorization-II/1-call-api/WebAPI
npm install
cd ../
cd WebApp
npm installThere are two projects in this sample. Each needs to be separately registered in your Azure AD tenant. To register these projects, you can:
- follow the steps below for manually register your apps
- or use PowerShell scripts that:
- automatically creates the Azure AD applications and related objects (passwords, permissions, dependencies) for you.
- modify the projects' configuration files.
Expand this section if you want to use this automation:
⚠️ If you have never used Azure AD Powershell before, we recommend you go through the App Creation Scripts once to ensure that your environment is prepared correctly for this step.
-
On Windows, run PowerShell as Administrator and navigate to the root of the cloned directory
-
If you have never used Azure AD Powershell before, we recommend you go through the App Creation Scripts once to ensure that your environment is prepared correctly for this step.
-
In PowerShell run:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force
-
Run the script to create your Azure AD application and configure the code of the sample application accordingly.
-
In PowerShell run:
cd .\AppCreationScripts\ .\Configure.ps1
Other ways of running the scripts are described in App Creation Scripts The scripts also provide a guide to automated application registration, configuration and removal which can help in your CI/CD scenarios.
As a first step you'll need to:
- Sign in to the Azure portal.
- If your account is present in more than one Azure AD tenant, select your profile at the top right corner in the menu on top of the page, and then switch directory to change your portal session to the desired Azure AD tenant.
- Navigate to the Azure portal and select the Azure AD service.
- Select the App Registrations blade on the left, then select New registration.
- In the Register an application page that appears, enter your application's registration information:
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
msal-node-webapi. - Under Supported account types, select Accounts in this organizational directory only.
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
- Select Register to create the application.
- In the app's registration screen, find and note the Application (client) ID. You use this value in your app's configuration file(s) later in your code.
- Select Save to save your changes.
- In the app's registration screen, select the Certificates & secrets blade in the left to open the page where you can generate secrets and upload certificates.
- In the Client secrets section, select New client secret:
- Type a key description (for instance
app secret), - Select one of the available key durations (6 months, 12 months or Custom) as per your security posture.
- The generated key value will be displayed when you select the Add button. Copy and save the generated value for use in later steps.
- You'll need this key later in your code's configuration files. This key value will not be displayed again, and is not retrievable by any other means, so make sure to note it from the Azure portal before navigating to any other screen or blade.
- Type a key description (for instance
- In the app's registration screen, select the Expose an API blade to the left to open the page where you can declare the parameters to expose this app as an API for which client applications can obtain access tokens for.
The first thing that we need to do is to declare the unique resource URI that the clients will be using to obtain access tokens for this API. To declare an resource URI, follow the following steps:
- Select
Setnext to the Application ID URI to generate a URI that is unique for this app. - For this sample, accept the proposed Application ID URI (
api://{clientId}) by selecting Save.
- Select
- All APIs have to publish a minimum of one scope for the client's to obtain an access token successfully. To publish a scope, follow these steps:
- Select Add a scope button open the Add a scope screen and Enter the values as indicated below:
- For Scope name, use
access_as_user. - Select Admins and users options for Who can consent?.
- For Admin consent display name type
Access msal-node-webapi. - For Admin consent description type
Allows the app to access msal-node-webapi as the signed-in user. - For User consent display name type
Access msal-node-webapi. - For User consent description type
Allow the application to access msal-node-webapi on your behalf. - Keep State as Enabled.
- Select the Add scope button on the bottom to save this scope.
- For Scope name, use
- Select Add a scope button open the Add a scope screen and Enter the values as indicated below:
- Select the
Manifestblade on the left.- Set
accessTokenAcceptedVersionproperty to 2. - Click on Save.
- Set
Open the project in your IDE (like Visual Studio or Visual Studio Code) to configure the code.
In the steps below, "ClientID" is the same as "Application ID" or "AppId".
- Open the
WebAPI\config.jsonfile. - Find the key
clientIdand replace the existing value with the application ID (clientId) ofmsal-node-webapiapp copied from the Azure portal. - Find the key
tenantIdand replace the existing value with your Azure AD tenant ID. - Find the key
clientSecretand replace the existing value with the key you saved during the creation ofmsal-node-webapicopied from the Azure portal.
- Navigate to the Azure portal and select the Azure AD service.
- Select the App Registrations blade on the left, then select New registration.
- In the Register an application page that appears, enter your application's registration information:
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
msal-node-webapp. - Under Supported account types, select Accounts in this organizational directory only.
- In the Redirect URI (optional) section, select Web in the combo-box and enter the following redirect URI:
http://localhost:4000/redirect.
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
- Select Register to create the application.
- In the app's registration screen, find and note the Application (client) ID. You use this value in your app's configuration file(s) later in your code.
- Select Save to save your changes.
- In the app's registration screen, select the Certificates & secrets blade in the left to open the page where you can generate secrets and upload certificates.
- In the Client secrets section, select New client secret:
- Type a key description (for instance
app secret), - Select one of the available key durations (6 months, 12 months or Custom) as per your security posture.
- The generated key value will be displayed when you select the Add button. Copy and save the generated value for use in later steps.
- You'll need this key later in your code's configuration files. This key value will not be displayed again, and is not retrievable by any other means, so make sure to note it from the Azure portal before navigating to any other screen or blade.
- Type a key description (for instance
- In the app's registration screen, select the API permissions blade in the left to open the page where we add access to the APIs that your application needs.
- Select the Add a permission button and then,
- Ensure that the My APIs tab is selected.
- In the list of APIs, select the API
msal-node-webapi. - In the Delegated permissions section, select the Access 'msal-node-webapi' in the list. Use the search box if necessary.
- Select the Add permissions button at the bottom.
Open the project in your IDE (like Visual Studio or Visual Studio Code) to configure the code.
In the steps below, "ClientID" is the same as "Application ID" or "AppId".
- Open the
WebApp\appSettings.jsonfile. - Find the key
clientIdand replace the existing value with the application ID (clientId) ofmsal-node-webappapp copied from the Azure portal. - Find the key
tenantIdand replace the existing value with your Azure AD tenant ID. - Find the key
clientSecretand replace the existing value with the key you saved during the creation ofmsal-node-webappcopied from the Azure portal. - Find the key
redirectUriand replace the existing value with the Redirect URI formsal-node-webapp. (by defaulthttp://localhost:4000/). - Find the key
postLogoutRedirectUriand replace the existing value with the base address ofmsal-node-webapp(by defaulthttp://localhost:4000/).
The rest of the key-value pairs are for resources/APIs that you would like to call. They are set as default, but you can modify them as you wish:
"<name of your resource>": {
"callingPageRoute": "<route where this resource will be called from, e.g. '/webapi'>",
"endpoint": "<URI coordinates of the resource, e.g. 'http://localhost:5000/myapi'>",
"scopes": ["scope for the resource, e.g. 'api://xxxxxx/access_as_user' ", "..."]
},Locate the root of the sample folder. Then:
cd WebAPI
npm startIn a separate terminal window, type:
cd ../
cd WebApp
npm start- Open your browser and navigate to
http://localhost:4000. - Select the Sign-in button on the top right corner.
- Once you sign-in, select on the Call web API.
ℹ️ Did the sample not work for you as expected? Then please reach out to us using the GitHub Issues page.
Were we successful in addressing your learning objective? Consider taking a moment to share your experience with us.
Configure your application:
- Initialize client applications using MSAL.js
- Single sign-on with MSAL.js
- Handle MSAL.js exceptions and errors
- Logging in MSAL.js applications
- Pass custom state in authentication requests using MSAL.js
- Prompt behavior in MSAL.js interactive requests
Learn more about the Microsoft identity platform:
- Microsoft identity platform (Azure Active Directory for developers)
- Overview of Microsoft Authentication Library (MSAL)
- Understanding Azure AD application consent experiences
- Understand user and admin consent
- Microsoft identity platform and OpenID Connect protocol
- Microsoft Identity Platform ID Tokens
For more information about how OAuth 2.0 protocols work in this scenario and other scenarios, see Authentication Scenarios for Azure AD.
Use Stack Overflow to get support from the community.
Ask your questions on Stack Overflow first and browse existing issues to see if someone has asked your question before.
Make sure that your questions or comments are tagged with [azure-active-directory node.js ms-identity adal msal].
If you find a bug in the sample, raise the issue on GitHub Issues.
To provide feedback on or suggest features for Azure Active Directory, visit User Voice page.
If you'd like to contribute to this sample, see CONTRIBUTING.MD.
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.

