| page_type | sample | ||||
|---|---|---|---|---|---|
| languages |
|
||||
| products |
|
||||
| name | A Node.js & Express Web App calling Microsoft Graph API using MSAL Node | ||||
| urlFragment | ms-identity-javascript-nodejs-tutorial | ||||
| description | This sample demonstrates a Node.js Express Web App application that authenticates users against Azure AD and obtains access token to call Microsoft Graph |
- 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 that authenticates users against Azure Active Directory (Azure AD) and obtains Access Tokens to call Microsoft Graph API (Graph API) and Azure Resource Manager API (ARM API), with the help of Microsoft Authentication Library for Node.js (MSAL Node). In doing so, it also illustrates various authorization concepts, such as OAuth 2.0 Authorization Code Grant, Dynamic Scopes and Incremental Consent, working with multiple resources 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 (Graph API or ARM API).
- 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/ |
List of changes to the sample. |
App/ |
Express application source folder. |
App/utils |
Contains msal-node helper classes. |
app.js |
Application entry point. |
App/routes/router.js |
Controllers and msal-node helper middleware. |
- Node.js must be installed to run this sample.
- A modern web browser. This sample uses ES6 conventions and will not run on Internet Explorer.
- Visual Studio Code is recommended for running and editing this sample.
- 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. Therefore, if you signed in to the Azure portal with a personal account and have never created a user account in your directory before, you need to do that now.
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:
npm installThere is one project in this sample. To register it, 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
ExpressWebApp. - 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 we 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 (In 1 year, In 2 years, or Never Expires) as per your security posture.
- The generated key value will be displayed when you select the Add button. Copy the generated value for use in the steps later.
- 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 Microsoft APIs tab is selected.
- In the Commonly used Microsoft APIs section, select Microsoft Graph
- In the Delegated permissions section, select the User.Read in the list. Use the search box if necessary.
- Select the Add permissions button at the bottom.
- Still in the API permissions blade,
- Select the Add a permission button and then,
- Ensure that the Microsoft APIs tab is selected.
- In the Commonly used Microsoft APIs section, select Azure Service Management
- In the Delegated permissions section, select the user_impersonation 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
auth.jsonfile. - Find the key
clientIdand replace the existing value with the application ID (clientId) of theExpressWebAppapplication 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 of theExpressWebAppapp, in the Azure Portal. - Find the key
homePageRouteand replace the existing value with the route that you wish to be redirected after sign-in, e.g./home. - Find the key
redirectUriand replace the existing value with the Redirect URI forExpressWebAppapp. For example,http://localhost:4000/redirect. - Find the
postLogoutRedirectUriand replace the existing value with the URI that you wish to be redirected after sign-out, e.g.http://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:
"nameOfYourResource": {
"callingPageRoute": "/<route_where_this_resource_will_be_called_from>",
"endpoint": "<uri_coordinates_of_the_resource>",
"scopes": ["scope1_of_the_resource", "scope1_of_the_resource", "..."]
},Locate the root of the sample folder. Then:
npm start- Open your browser and navigate to
http://localhost:4000. - Click the Sign-in button on the top right corner.
- Once you sign-in, click on the See my profile button to call Microsoft Graph.
- Once you sign-in, click on the Get my tenant button to call Azure Resource Manager.
ℹ️ 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.
In order to access a protected resource on behalf of a signed-in user, the app needs to present a valid Access Token to that resource owner (for example, Microsoft Graph). The intended recipient of an Access Token is represented by the aud claim (in this case, it should be the Microsoft Graph API's App ID); in case the value for the aud claim does not mach the resource APP ID URI, the token should be considered invalid. Likewise, the permissions that an Access Token grants is represented by the scp claim. See Access Token claims for more information.
Scopes can come in various forms so it pays off to be familiar with them. The following are all resource scopes:
user.read- short-hand expression for Microsoft Graph User resource scopehttps://management.azure.com/user_impersonation- https expression of a multi-tenant resource scopeapi://9k8521c1-bab5-1256-a87b-574f83c463z6/access_as_user- expression of a single-tenant resource (e.g. custom web API) scope
In the code snippet above, the user will be prompted for consent once they authenticate and receive an ID Token and an Access Token with scope User.Read. Later, if they request an Access Token for User.Read, they will not be asked for consent again (in other words, they can acquire a token silently). On the other hand, the user did not consented to Mail.Read at the authentication stage. As such, they will be asked for consent when requesting an Access Token for that scope. The token received will contain all the previously consented scopes, hence the term incremental consent.
When you have to access different resources (for instance, Microsoft Graph API and Azure Resource Manager API), initiate a separate token request for each:
Bear in mind that you can request multiple scopes for the same resource (e.g. User.Read, User.Write and Calendar.Read for Graph API).
In case you erroneously pass multiple resources in your token request, the token you will receive will only be issued for the first resource.
Clients should treat access tokens as opaque strings, as the contents of the token are intended for the resource only (such as a web API or Microsoft Graph). For validation and debugging purposes, developers can decode JWTs (JSON Web Tokens) using a site like jwt.ms.
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 azure-ad-b2c 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.

