- 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 (MS Graph) and Azure Resource Manager API (ARM API), with the help of Microsoft Authentication Library for Node.js (MSAL Node). In doing so, it illustrates authorization concepts such as OAuth 2.0 Authorization Code Grant, dynamic scopes and incremental consent, working with multiple resources and more.
This sample also demonstrates how to use the Microsoft Graph JavaScript SDK for working with the Microsoft Graph API.
ℹ️ Check out the community call: An introduction to Microsoft Graph for developers
- The client application uses MSAL Node (via msal-express-wrapper) 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 server (MS Graph or Azure REST API).
- The resource server responds with the resource that the user has access to.
| File/folder | Description |
|---|---|
AppCreationScripts/ |
Contains Powershell scripts to automate app registration. |
ReadmeFiles/ |
Contains illustrations and screenshots. |
App/appSettings.js |
Authentication parameters and settings. |
App/app.js |
Application entry point. |
App/utils/graphManager.js |
Handles calls to Microsoft Graph using Graph JS SDK. |
App/utils/fetchManager.js |
Handles calls to protected APIs using Axios package. |
- 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 2-Authorization/1-call-graph/App
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.
- 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-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 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.
- Select the Add a permission button and then:
- Ensure that the Microsoft APIs tab is selected.
- In the list of APIs, select the API
Windows Azure Service Management API. - 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.
- Select the Add a permission button and then:
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
App/appSettings.jsfile. - 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
redirectand replace the existing value with the Redirect URI formsal-node-webapp. (by defaulthttp://localhost:4000/redirect).
ℹ️ For
redirectUri, you can simply enter the path component of the URI instead of the full URI. For example, instead ofhttp://localhost:4000/redirect, you can simply enter/redirect. This may come in handy in deployment scenarios.
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:
{
remoteResources: {
nameOfYourResource: {
endpoint: "<uri_coordinates_of_the_resource>",
scopes: ["scope1_of_the_resource", "scope2_of_the_resource", "..."]
},
}
}- Open the
App/app.jsfile. - Find the string
ENTER_YOUR_SECRET_HEREand replace it with a secret that will be used when encrypting your app's session using the express-session package.
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. a custom web API) scope
const express = require('express');
const session = require('express-session');
const msalWrapper = require('msal-express-wrapper');
// initialize express
const app = express();
app.use(session({
secret: 'ENTER_YOUR_SECRET_HERE',
resave: false,
saveUninitialized: false,
cookie: {
secure: false, // set this to true on production
}
}));
// instantiate the wrapper
const authProvider = new msalWrapper.AuthProvider(config);
// initialize the wrapper
app.use(authProvider.initialize());
// authentication routes
app.get('/signin',
authProvider.signIn({
successRedirect: '/'
}
));
app.get('/signout',
authProvider.signOut({
successRedirect: '/'
}
));
app.get('/profile',
authProvider.getToken({
resource: config.remoteResources.graphAPI
}),
mainController.getProfilePage
);
app.get('/tenant',
authProvider.getToken({
resource: config.remoteResources.armAPI
}),
mainController.getTenantPage
);
app.listen(SERVER_PORT, () => console.log(`Msal Node Auth Code Sample app listening on port ${SERVER_PORT}!`));Under the hood, the getToken() middleware grabs resource endpoint and associated scope from appSettings.js, and attempts to obtain an access token from cache silently and attaches it to session. If silent token acquisition fails for some reason (e.g. consent required), it makes an auth code request, which triggers the first leg of auth code flow.
getToken = (options: TokenRequestOptions): RequestHandler => {
return async (req: Request, res: Response, next: NextFunction): Promise<void> => {
// get scopes for token request
const scopes = options.resource.scopes;
const resourceName = this.getResourceNameFromScopes(scopes)
if (!req.session.remoteResources) {
req.session.remoteResources = {};
}
req.session.remoteResources = {
[resourceName]: {
...this.appSettings.remoteResources[resourceName],
accessToken: null,
} as Resource
};
try {
const silentRequest: SilentFlowRequest = {
account: req.session.account,
scopes: scopes,
};
// acquire token silently to be used in resource call
const tokenResponse = await this.msalClient.acquireTokenSilent(silentRequest);
console.log("\nSuccessful silent token acquisition:\n Response: \n:", tokenResponse);
// In B2C scenarios, sometimes an access token is returned empty.
// In that case, we will acquire token interactively instead.
if (StringUtils.isEmpty(tokenResponse.accessToken)) {
console.log(ErrorMessages.TOKEN_NOT_FOUND);
throw new InteractionRequiredAuthError(ErrorMessages.INTERACTION_REQUIRED);
}
req.session.remoteResources[resourceName].accessToken = tokenResponse.accessToken;
next();
} catch (error) {
// in case there are no cached tokens, initiate an interactive call
if (error instanceof InteractionRequiredAuthError) {
const state = this.cryptoProvider.base64Encode(
JSON.stringify({
stage: AppStages.ACQUIRE_TOKEN,
path: req.route.path,
nonce: req.session.nonce,
})
);
const params: AuthCodeParams = {
authority: this.msalConfig.auth.authority,
scopes: scopes,
state: state,
redirect: UrlUtils.ensureAbsoluteUrl(req, this.appSettings.authRoutes.redirect),
account: req.session.account,
};
// get an auth code url and initiate the first leg of auth code grant to get token
return this.getAuthCode(req, res, next, params);
} else {
console.log(error);
next(error);
}
}
}
};In the second leg of auth code flow, the auth code from redirect response is used to request a new access token (and refresh token) via the handleRedirect middleware.
private handleRedirect = (options?: HandleRedirectOptions): RequestHandler => {
return async (req: Request, res: Response, next: NextFunction): Promise<void> => {
if (req.query.state) {
const state = JSON.parse(this.cryptoProvider.base64Decode(req.query.state as string));
// check if nonce matches
if (state.nonce === req.session.nonce) {
switch (state.stage) {
// ...
case AppStages.ACQUIRE_TOKEN: {
// get the name of the resource associated with scope
const resourceName = this.getResourceNameFromScopes(req.session.tokenRequest.scopes);
req.session.tokenRequest.code = req.query.code as string
try {
const tokenResponse = await this.msalClient.acquireTokenByCode(req.session.tokenRequest);
console.log("\nResponse: \n:", tokenResponse);
req.session.remoteResources[resourceName].accessToken = tokenResponse.accessToken;
res.redirect(state.path);
} catch (error) {
console.log(ErrorMessages.TOKEN_ACQUISITION_FAILED);
console.log(error);
next(error);
}
break;
}
default:
console.log(ErrorMessages.CANNOT_DETERMINE_APP_STAGE);
res.redirect(this.appSettings.authRoutes.error);
break;
}
} else {
console.log(ErrorMessages.NONCE_MISMATCH);
res.redirect(this.appSettings.authRoutes.unauthorized);
}
} else {
console.log(ErrorMessages.STATE_NOT_FOUND)
res.redirect(this.appSettings.authRoutes.unauthorized);
}
}
};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 debugging purposes, developers can decode JWTs (JSON Web Tokens) using a site like jwt.ms.
The Microsoft Graph JavaScript SDK is a lightweight wrapper around the Microsoft Graph API that can be used server-side and in the browser. It provides an API that allows easy interaction when querying Microsoft Graph. While the SDK can handle token acquisition by itself in certain scenarios, we provide the access token in this sample as shown below:
const graph = require('@microsoft/microsoft-graph-client');
require('isomorphic-fetch');
/**
* Creating a Graph client instance via options method. For more information, visit:
* https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/CreatingClientInstance.md#2-create-with-options
*/
getAuthenticatedClient = (accessToken) => {
// Initialize Graph client
const client = graph.Client.init({
// Use the provided access token to authenticate requests
authProvider: (done) => {
done(null, accessToken);
}
});
return client;
}Then, in a controller, simply call the Graph via the graphClient:
exports.getProfilePage = async (req, res, next) => {
let profile;
try {
const graphClient = graphManager.getAuthenticatedClient(req.session.remoteResources["graphAPI"].accessToken);
profile = await graphClient
.api('/me')
.get();
} catch (error) {
console.log(error)
}
res.render('profile', { isAuthenticated: req.session.isAuthenticated, profile: profile });
}To call any other protected API, simply make a http GET request to the resource endpoint using the bearer token authentication scheme as shown below:
const { default: axios } = require('axios');
callAPI = async(endpoint, accessToken) => {
if (!accessToken || accessToken === "") {
throw new Error('No tokens found')
}
const options = {
headers: {
Authorization: `Bearer ${accessToken}`
}
};
console.log('request made to web API at: ' + new Date().toString());
try {
const response = await axios.default.get(endpoint, options);
return response.data;
} catch(error) {
console.log(error)
return error;
}
}Then, in a controller, simply call the utility method:
exports.getTenantPage = async (req, res, next) => {
let tenant;
try {
tenant = await fetchManager.callAPI(appSettings.remoteResources.armAPI.endpoint, req.session.remoteResources["armAPI"].accessToken);
} catch (error) {
console.log(error)
}
res.render('tenant', { isAuthenticated: req.session.isAuthenticated, tenant: tenant.value[0] });
}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 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.

