page_type | name | description | languages | products | urlFragment | extensions | |||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
sample |
A React SPA with a Node.Js (Express) back-end using the Backend For Frontend (BFF) Proxy architecture to authenticate users with Azure AD and calling Microsoft Graph |
A React SPA with a Node.Js (Express) back-end using the Backend For Frontend (BFF) Proxy architecture to authenticate users with Azure AD and calling Microsoft Graph on the user's behalf |
|
|
ms-identity-javascript-nodejs-tutorial |
|
A React SPA with a Node.js (Express) web app using the Backend For Frontend (BFF) Proxy architecture to authenticate users with Azure AD and call Microsoft Graph
- Overview
- Scenario
- Contents
- Prerequisites
- Setup the sample
- Explore the sample
- Troubleshooting
- About the code
- Next Steps
- Contributing
- Learn More
This sample demonstrates a React single-page application (SPA) with an Node.js Express backend that authenticates users and calls the Microsoft Graph API using the backend for frontend (BFF) proxy architecture. In this architecture, access tokens are retrieved and stored within the secure backend context, and the client side JavaScript application, which is served by the Express web app, is only indirectly involved in the authN/authZ process by routing the token and API requests to the backend. The trust between the frontend and backend is established via a secure cookie upon successful sign-in.
ℹ️ To learn how applications integrate with Microsoft Graph, consider going through the recorded session: An introduction to Microsoft Graph for developers
- The client-side React SPA initiates token acquisition by calling the login endpoint of the Express web app.
- Express web app uses MSAL Node to sign-in a user and obtain a JWT ID Token and an Access Token from Azure AD.
- Express web app uses the access token as a bearer token to authorize the user to call the Microsoft Graph API protected by Azure AD.
- Express web app returns the Microsoft Graph
/me
endpoint response back to the React SPA.
sequenceDiagram
participant Frontend
participant Backend
participant Azure AD
participant Graph
Frontend-)+Backend: /login
Backend-)+Azure AD: login.microsoftonline.com
Azure AD--)-Backend: token response
Backend--)-Frontend: /login response (auth state)
Frontend-)+Backend: /profile
Backend-)+Graph: graph.microsoft.com/v1.0/me
Graph--)-Backend: /me endpoint response
Backend--)-Frontend: /profile response (/me data)
File/folder | Description |
---|---|
app.js |
Application entry point. |
authConfig.js |
Contains authentication configuration parameters. |
auth/AuthProvider.js |
A custom wrapper around MSAL Node for authN/authZ. |
utils/graphClient |
Instantiates Graph SDK client using a custom authentication provider. |
client/src/context/AuthContext |
React context to fetch user information from the backend. |
client/src/pages/Profile |
Calls auth/profile route on backend to call the Microsoft Graph /me endpoint |
- 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.
- An Azure AD tenant. For more information, see: How to get an Azure AD tenant
- A user account in your Azure AD tenant.
From your shell or command line:
git clone https://github.com/Azure-Samples/ms-identity-javascript-nodejs-tutorial.git
or download and extract the repository .zip file.
⚠️ To avoid path length limitations on your operating system, we recommend cloning into a directory near the root of your drive.
cd 5-AdvancedScenarios\1-call-graph-bff\App
npm install
There 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 Microsoft Graph PowerShell before, we recommend you go through the App Creation Scripts Guide once to ensure that your environment is prepared correctly for this step.
-
Ensure that you have PowerShell 7 or later.
-
Run the script to create your Azure AD application and configure the code of the sample application accordingly.
-
For interactive process -in PowerShell, run:
cd .\AppCreationScripts\ .\Configure.ps1 -TenantId "[Optional] - your tenant id" -AzureEnvironmentName "[Optional] - Azure environment, defaults to 'Global'"
Other ways of running the scripts are described in App Creation Scripts guide. The scripts also provide a guide to automated application registration, configuration and removal which can help in your CI/CD scenarios.
ℹ️ This sample can make use of client certificates. You can use AppCreationScripts to register an Azure AD application with certificates. See: How to use certificates instead of client secrets
To manually register the apps, 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 Active Directory 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
- Select Register to create the application.
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
- In the Overview blade, find and note the Application (client) ID. You use this value in your app's configuration file(s) later in your code.
- In the app's registration screen, select the Authentication blade to the left.
- If you don't have a platform added, select Add a platform and select the Web option.
- In the Redirect URI section enter the following redirect URI:
http://localhost:4000/auth/redirect
- Click Save to save your changes.
- In the Redirect URI section enter the following redirect URI:
- 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.
⚠️ For enhanced security, consider using certificates instead of client secrets. See: How to use certificates instead of secrets. - Type a key description (for instance
- Since this app signs-in users, we will now proceed to select delegated permissions, which is is required by apps signing-in users.
- 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 User.Read in the list. Use the search box if necessary.
- Select the Add permissions button at the bottom.
- Still on the same app registration, select the Token configuration blade to the left.
- Select Add optional claim:
- Select optional claim type, then choose ID.
- Select the optional claim acct.
Provides user's account status in tenant. If the user is a member of the tenant, the value is 0. If they're a guest, the value is 1.
- Select Add to save your changes.
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\authConfig.js
file. -
Find the key
Enter_the_Application_Id_Here
and replace the existing value with the application ID (clientId) ofmsal-node-webapp
app copied from the Azure portal. -
Find the key
Enter_the_Tenant_Id_Here
and replace the existing value with your Azure AD tenant/directory ID. -
Find the key
Enter_the_Client_Secret_Here
and replace the existing value with the generated secret that you saved during the creation ofmsal-node-webapp
copied from the Azure portal. -
Open the
App/app.js
file. -
Find the string
ENTER_YOUR_SECRET_HERE
and replace it with a secret that will be used when encrypting your app's session using the express-session package.
cd 5-AdvancedScenarios\1-call-graph-bff\App
npm start
- Open your browser and navigate to
http://localhost:4000
. - Select the Sign In button on the top right corner.
- Select the Profile button on the navigation bar. This will make a call to the Graph 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.
Expand for troubleshooting info
- 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. 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 [
msal-node
node
ms-identity
adal
msal-js
msal
].
To provide feedback on or suggest features for Azure Active Directory, visit User Voice page.
In AuthProvider.js, MSAL Node ConfidentialClientApplication is configured to obtain tokens to call downstream web APIs (here, Microsoft Graph) using OAuth 2.0 authorization code grant:
async acquireToken(req, res, next, options) {
const msalInstance = this.getMsalInstance();
try {
msalInstance.getTokenCache().deserialize(req.session.tokenCache);
const tokenResponse = await msalInstance.acquireTokenSilent({
account: req.session.account,
scopes: options.scopes || [],
claims: getClaims(req.session, this.config.msalConfig.auth.clientId),
});
req.session.tokenCache = msalInstance.getTokenCache().serialize();
req.session.accessToken = tokenResponse.accessToken;
req.session.idToken = tokenResponse.idToken;
req.session.account = tokenResponse.account;
return tokenResponse;
} catch (error) {
if (error instanceof InteractionRequiredAuthError) {
// handle interaction error
} else {
throw error;
}
}
}
On the frontend side, the React SPA uses the AuthContext, which makes a GET call to the /auth/login
endpoint of the Express web app.
login = (postLoginRedirectUri) => {
let url = "api/auth/login";
const searchParams = new URLSearchParams({});
if (postLoginRedirectUri) {
searchParams.append('postLoginRedirectUri', encodeURIComponent(postLoginRedirectUri));
}
url = `${url}?${searchParams.toString()}`;
window.location.replace(url);
}
The controller in authController.js processes the request and initiates a token request against Azure AD, using the AuthProvider class which wraps MSAL Node for simplicity:
exports.loginUser = async (req, res, next) => {
let postLoginRedirectUri;
let scopesToConsent;
if (req.query && req.query.postLoginRedirectUri) {
postLoginRedirectUri = decodeURIComponent(req.query.postLoginRedirectUri);
}
if (req.query && req.query.scopesToConsent) {
scopesToConsent = decodeURIComponent(req.query.scopesToConsent);
}
return authProvider.login(req, res, next, { postLoginRedirectUri, scopesToConsent });
}
Once the authentication is successful, the authentication state can be shared with the frontend. The claims in the user's ID token is sent back to the frontend to update the UI via the /auth/account
endpoint.
The sample makes use of HTTP only, strict cookies to secure the calls between the frontend and the backend. This is configured in app.js;
const express = require('express');
const session = require('express-session');
const sessionConfig = {
name: SESSION_COOKIE_NAME,
secret: 'ENTER_YOUR_SECRET_HERE', // replace with your own secret
resave: false,
saveUninitialized: false,
cookie: {
sameSite: 'strict',
httpOnly: true,
secure: false, // set this to true on production
},
};
if (app.get('env') === 'production') {
app.set('trust proxy', 1); // trust first proxy e.g. App Service
sessionConfig.cookie.secure = true; // serve secure cookies on production
}
app.use(session(sessionConfig));
Continuous access evaluation (CAE) enables applications to do just-in time token validation, for instance enforcing user session revocation in the case of password change/reset but there are other benefits. For details, see Continuous access evaluation.
Microsoft Graph is now CAE-enabled in Preview. This means that it can ask its client apps for more claims when conditional access policies require it. Your can enable your application to be ready to consume CAE-enabled APIs by:
- Declaring that the client app is capable of handling claims challenges.
- Processing these challenges when they are thrown by the web API
This sample app declares that it's CAE-capable by adding the clientCapabilities
property in the configuration in authConfig.js:
const msalConfig = {
auth: {
clientId: 'Enter_the_Application_Id_Here',
authority: 'https://login.microsoftonline.com/Enter_the_Tenant_Info_Here',
clientCapabilities: ["CP1"] // this lets the resource owner know that this client is capable of handling claims challenge.
}
}
const msalInstance = new ConfidentialClientApplication(msalConfig);
When a CAE event occurs, the Graph service return a response with the WWW-Authenticate header and a 401 status code. You can parse this header and retrieve the claims challenge inside. Here, we set the challenge as a session variable, and a 401 status is sent to the frontend afterwards, indicating that another login request must be made. When that happens, the claims are retrieved back from the session:
exports.getProfile = async (req, res, next) => {
try {
const tokenResponse = await authProvider.acquireToken(req, res, next, { scopes: ['User.Read']});
const graphResponse = await getGraphClient(tokenResponse.accessToken).api('/me').responseType('raw').get();
const graphData = await handleAnyClaimsChallenge(graphResponse);
res.status(200).json(graphData);
} catch (error) {
if (error.name === 'ClaimsChallengeAuthError') {
setClaims(req.session, msalConfig.auth.clientId, error.payload);
return res.status(401).json({ error: error.name });
}
next(error);
}
}
// ...
const handleAnyClaimsChallenge = async (response) => {
if (response.status === 200) {
return await response.json();
}
if (response.status === 401) {
if (response.headers.get("WWW-Authenticate")) {
const authenticateHeader = response.headers.get("WWW-Authenticate");
const claimsChallenge = parseChallenges(authenticateHeader);
const err = new Error("A claims challenge has occurred");
err.payload = claimsChallenge.claims;
err.name = 'ClaimsChallengeAuthError';
throw err;
}
throw new Error(`Unauthorized: ${response.status}`);
}
throw new Error(`Something went wrong with the request: ${response.status}`);
};
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.
For more details on what's inside the access token, clients should use the token response data that's returned with the access token to your client. When your client requests an access token, the Microsoft identity platform also returns some metadata about the access token for your app's consumption. This information includes the expiry time of the access token and the scopes for which it's valid. For more details about access tokens, please see Microsoft identity platform access tokens
Microsoft Graph JavaScript SDK provides various utility methods to query the Graph API. While the SDK has a default authentication provider that can be used in basic scenarios, it can also be extended to use with a custom authentication provider such as MSAL. To do so, we will initialize the Graph SDK client with an authProvider function. In this case, user has to provide their own implementation for getting and refreshing accessToken. A callback will be passed into this authProvider
function, accessToken or error needs to be passed in to that callback.
export const getGraphClient = (accessToken) => {
// Initialize Graph client
const graphClient = Client.init({
// Use the provided access token to authenticate requests
authProvider: (done) => {
done(null, accessToken);
},
});
return graphClient;
};
Learn how to:
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 [email protected] with any additional questions or comments.
- Microsoft identity platform (Azure Active Directory for developers)
- Azure AD code samples
- Overview of Microsoft Authentication Library (MSAL)
- Register an application with the Microsoft identity platform
- Configure a client application to access web APIs
- Understanding Azure AD application consent experiences
- Understand user and admin consent
- Application and service principal objects in Azure Active Directory
- Authentication Scenarios for Azure AD
- Building Zero Trust ready apps
- National Clouds
- 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
- Use MSAL.js to work with Azure AD B2C