Skip to content

Latest commit

 

History

History
455 lines (342 loc) · 24.9 KB

File metadata and controls

455 lines (342 loc) · 24.9 KB
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 Microsoft Entra ID 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 Microsoft Entra ID and calling Microsoft Graph on the user's behalf
javascript
microsoft-entra-id
msal-js
msal-node
ms-graph
ms-identity-javascript-nodejs-tutorial
services
ms-identity
platform
JavaScript
endpoint
Microsoft Entra ID v2.0
level
300
client
React SPA with Express backend
service
MS Graph

A React SPA with a Node.js (Express) web app using the Backend For Frontend (BFF) Proxy architecture to authenticate users with Microsoft Entra ID and call Microsoft Graph

Overview

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

Scenario

  1. The client-side React SPA initiates token acquisition by calling the login endpoint of the Express web app.
  2. Express web app uses MSAL Node to sign-in a user and obtain a JWT ID Token and an Access Token from Microsoft Entra ID.
  3. Express web app uses the access token as a bearer token to authorize the user to call the Microsoft Graph API protected by Microsoft Entra ID.
  4. Express web app returns the Microsoft Graph /me endpoint response back to the React SPA.
sequenceDiagram
    participant Frontend
    participant Backend
    participant Microsoft Entra ID
    participant Graph
    Frontend-)+Backend: /login
    Backend-)+Microsoft Entra ID: login.microsoftonline.com
    Microsoft Entra ID--)-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)
Loading

Contents

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

Prerequisites

Setup the sample

Step 1: Clone or download this repository

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.

Step 2: Install project dependencies

    cd 5-AdvancedScenarios\1-call-graph-bff\App
    npm install

Step 3: Register the sample application(s) in your tenant

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 Microsoft Entra 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.

  1. Ensure that you have PowerShell 7 or later.

  2. Run the script to create your Microsoft Entra application and configure the code of the sample application accordingly.

  3. 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 a Microsoft Entra application with certificates. See: How to use certificates instead of client secrets

Choose the Microsoft Entra tenant where you want to create your applications

To manually register the apps, as a first step you'll need to:

  1. Sign in to the Microsoft Entra admin center.
  2. If your account is present in more than one Microsoft Entra 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 Microsoft Entra tenant.

Register the service app (msal-node-webapp)

  1. Navigate to the Microsoft Entra admin center and select the Microsoft Entra ID service.
  2. Select the App Registrations blade on the left, then select New registration.
  3. In the Register an application page that appears, enter your application's registration information:
    1. In the Name section, enter a meaningful application name that will be displayed to users of the app, for example msal-node-webapp.
    2. Under Supported account types, select Accounts in this organizational directory only
    3. Select Register to create the application.
  4. 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.
  5. In the app's registration screen, select the Authentication blade to the left.
  6. If you don't have a platform added, select Add a platform and select the Web option.
    1. In the Redirect URI section enter the following redirect URI:
      1. http://localhost:4000/auth/redirect
    2. Click Save to save your changes.
  7. 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.
  8. In the Client secrets section, select New client secret:
    1. Type a key description (for instance app secret).
    2. Select one of the available key durations (6 months, 12 months or Custom) as per your security posture.
    3. The generated key value will be displayed when you select the Add button. Copy and save the generated value for use in later steps.
    4. 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 Microsoft Entra admin center 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.

  9. Since this app signs-in users, we will now proceed to select delegated permissions, which is is required by apps signing-in users.
    1. 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:
    2. Select the Add a permission button and then:
    3. Ensure that the Microsoft APIs tab is selected.
    4. In the Commonly used Microsoft APIs section, select Microsoft Graph
    5. In the Delegated permissions section, select User.Read in the list. Use the search box if necessary.
    6. Select the Add permissions button at the bottom.
Configure Optional Claims
  1. Still on the same app registration, select the Token configuration blade to the left.
  2. Select Add optional claim:
    1. Select optional claim type, then choose ID.
    2. 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.

    1. Select Add to save your changes.
Configure the service app (msal-node-webapp) to use your app registration

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".

  1. Open the APP\authConfig.js file.

  2. Find the key Enter_the_Application_Id_Here and replace the existing value with the application ID (clientId) of msal-node-webapp app copied from the Microsoft Entra admin center.

  3. Find the key Enter_the_Tenant_Id_Here and replace the existing value with your Microsoft Entra tenant/directory ID.

  4. Find the key Enter_the_Client_Secret_Here and replace the existing value with the generated secret that you saved during the creation of msal-node-webapp copied from the Microsoft Entra admin center.

  5. Open the App/app.js file.

  6. 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.

Step 4: Running the sample

    cd 5-AdvancedScenarios\1-call-graph-bff\App
    npm start

Explore the sample

  1. Open your browser and navigate to http://localhost:4000.
  2. Select the Sign In button on the top right corner.
  3. Select the Profile button on the navigation bar. This will make a call to the Graph API.

Screenshot

ℹ️ Did the sample not work for you as expected? Then please reach out to us using the GitHub Issues page.

We'd love your feedback!

Were we successful in addressing your learning objective? Consider taking a moment to share your experience with us.

Troubleshooting

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 Microsoft Entra ID, visit User Voice page.

About the code

Login and logout

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 Microsoft Entra ID, 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.

Cookie policies

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));

Handle Continuous Access Evaluation (CAE) challenge from Microsoft Graph

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:

  1. Declaring that the client app is capable of handling claims challenges.
  2. Processing these challenges when they are thrown by the web API

Declare the CAE capability in the configuration

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);

Processing the CAE challenge from Microsoft Graph

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}`);
};

Access token validation

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

Calling the Microsoft Graph API

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;
};

Next Steps

Learn how to:

Contributing

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.

Learn More