IvanFarkas / msal-react-call-api-pop

React SPA calling web API using Proof of Possession

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

React single-page application calling Node.js & Express web API using Proof of Possession

  1. Overview
  2. Scenario
  3. Contents
  4. Prerequisites
  5. Setup
  6. Registration
  7. Running the sample
  8. Explore the sample
  9. About the code
  10. More information
  11. Community Help and Support
  12. Contributing

Overview

This sample demonstrates a React SPA calling a Node.js & Express web API that is secured using Azure Active Directory (Azure AD). The SPA project is secured with the Microsoft Authentication Library for React (MSAL React), while the web API is secured with passport-azure-ad.

This sample demonstrates the Proof of Possession (PoP) authentication scheme. This authentication scheme cryptographically binds the access tokens to the browser and client application from which they are requested, meaning they cannot be used from a different application or device. This effectively prevents token replay attacks. The resource server that accepts the PoP token (i.e. a web API) needs to be able to decipher the incoming request for the PoP authentication scheme to work properly.

Scenario

  1. The client React SPA uses MSAL React to sign-in and obtain a JWT access token from Azure AD for the web API.
  2. The client React SPA wraps the access token in a secure envelope and stamps it with its signature using MSAL React.
  3. The access token then is used with PoP authentication scheme to authorize the user to call the web API protected by Azure AD.
  4. The web API decrypts the secure envelope to obtain the access token.
  5. Once the access token is validated, the web API responds with the protected resource.

Overview

Contents

File/folder Description
SPA/src/authConfig.js Authentication parameters for SPA project reside here.
SPA/src/index.js MSAL React is initialized here.
SPA/src/fetch.js Contains token acquisition and API call utilities.
API/authConfig.json Authentication parameters for API project reside here.
API/app.js Application entry. passport-azure-ad is initialized here.
API/utils/validateToken.js Contains utility methods for validating PoP tokens.

Prerequisites

Setup

Step 1. Clone or download this repository

git clone https://github.com/IvanFarkas/msal-react-call-api-pop.git

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

Step 2. Install Node.js & Express web API dependencies

cd API
npm install

Step 3. Install React SPA dependencies

cd ../SPA
npm install

Register the sample application(s) with your Azure Active Directory tenant

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

  1. On Windows, run PowerShell as Administrator and navigate to the root of the cloned directory

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

  3. In PowerShell run:

    Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force
  4. Run the script to create your Azure AD application and configure the code of the sample application accordingly.

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

Choose the Azure AD tenant where you want to create your applications

As a first step you'll need to:

  1. Sign in to the Azure portal.
  2. 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.

Register the service app (msal-node-api)

  1. Navigate to the Azure portal and select the Azure AD 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:
    • In the Name section, enter a meaningful application name that will be displayed to users of the app, for example msal-node-api.
    • Under Supported account types, select Accounts in this organizational directory only.
  4. Select Register to create the application.
  5. 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.
  6. Select Save to save your changes.
  7. 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 Set next 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.
  8. 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 the following 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-api.
      • For Admin consent description type Allows the app to access msal-node-api as the signed-in user.
      • For User consent display name type Access msal-node-api.
      • For User consent description type Allow the application to access msal-node-api on your behalf.
      • Keep State as Enabled.
      • Select the Add scope button on the bottom to save this scope.

Configure the service app (msal-node-api) 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 API\authConfig.json file.
  2. Find the string Application_Id and replace the existing value with the application ID (clientId) of msal-node-api app copied from the Azure portal.
  3. Find the string Tenant_Id and replace the existing value with your Azure AD tenant ID.

Register the client app (msal-react-spa)

  1. Navigate to the Azure portal and select the Azure AD 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:
    • In the Name section, enter a meaningful application name that will be displayed to users of the app, for example msal-react-spa.
    • Under Supported account types, select Accounts in this organizational directory only.
    • In the Redirect URI (optional) section, select Single-page application in the combo-box and enter the following redirect URI: http://localhost:3000/.
  4. Select Register to create the application.
  5. 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.
  6. Select Save to save your changes.
  7. 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-api.
    • In the Delegated permissions section, select the Access 'msal-node-api' in the list. Use the search box if necessary.
    • Select the Add permissions button at the bottom.

Configure the client app (msal-react-spa) 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 SPA\src\authConfig.js file.
  2. Find the string Application_Id and replace the existing value with the application ID (clientId) of msal-react-spa app copied from the Azure portal.
  3. Find the string Tenant_Id and replace the existing value with your Azure AD tenant ID.
  4. Find the string Web_Api_Scope_here and replace the existing value with the scope value you saved earlier (e.g., api://{Client_Id_of_Web_Api}/access_as_user.

Running the sample

Using a command line interface such as VS Code integrated terminal, locate the application directory. Then:

    cd SPA
    npm start

In a separate console window, execute the following commands:

    cd ..
    cd API
    npm start

Explore the sample

  1. Open your browser and navigate to http://localhost:3000.
  2. Sign-in using the button on the top-right corner.
  3. Select the TodoList button on the navigation bar to access your todo list.

Screenshot

About the code

Acquiring PoP tokens

In fetch.js, an async method is implemented to acquire tokens. The method first constructs a PoP token request, using the parameters provided. It then attempts to silently acquire a valid access token from the cache, or if that fails, using the popup window prompt. Once an access token is obtained, MSAL cryptographically signs the it with the browser and client app's signature.

Important to notice that PoP token is bound to the HTTP method and full endpoint URL that the PoP token will be used for (e.g. accessing a protected resource). See below the method and string parameters.

const getToken = async (method, query) => {
  const account = msalInstance.getActiveAccount();

  if (!account) {
    throw Error('No active account! Verify a user has been signed in and setActiveAccount has been called.');
  }

  const tokenRequest = {
    scopes: [...protectedResources.apiTodoList.scopes],
    authenticationScheme: AuthenticationScheme.POP,
    resourceRequestMethod: method,
    resourceRequestUri: query ? protectedResources.apiTodoList.endpoint + query : protectedResources.apiTodoList.endpoint,
  };

  try {
    const response = await msalInstance.acquireTokenSilent({
      account: account,
      ...tokenRequest,
    });

    // View JWT issued by AAD: https://jwt.ms
    console.log('accessToken:', response.accessToken);

    return response.accessToken;
  } catch (error) {
    if (InteractionRequiredAuthError.isInteractionRequiredError(error.errorCode)) {
      const response = await this.authService.acquireTokenPopup(tokenRequest);
      return response.accessToken;
    }
  }
};

Calling web API using PoP scheme

In fetch.js, getTasks() method returns a promise, which then you can use in your components (see TodoList.jsx).

export const getTasks = async () => {
  const accessToken = await getToken('GET');
  const headers = new Headers();
  const pop = `PoP ${accessToken}`;

  headers.append('Authorization', pop);

  const options = {
    method: 'GET',
    headers: headers,
  };

  return fetch(protectedResources.apiTodoList.endpoint, options)
    .then((response) => response.json())
    .catch((error) => console.error(error));
};

Validating PoP tokens

In validateToken.js, we first decode the token to grab the confirmation claim (cnf) that contains a JSON Web Key (JWK). Then, we parse this key, and use it to verify the signature of the token. Once this is done, we can verify the claims section of the token, importantly, the method, host and path claims. If the PoP token is valid, we pass the access token it envelops back to the Authorization header of the request as a bearer token and call the next middleware in the route, where it gets validated by the passport-azure-ad authentication middleware.

const validatePoP = async (req, res, next) => {
  // The access token the user sent
  const userToken = req.get('authorization').split(' ')[1];

  if (!userToken) {
    return res.status(401).json({
      error: 'Missing authorization header',
    });
  }

  const decodedToken = jwtDecode(userToken, { complete: true });

  try {
    // Parse the JSON Web Key sent in cnf claim to get the public key
    parsedToken = await parseJwk(decodedToken.payload.cnf.jwk, 'RS256');

    try {
      // Verify the original token using public key
      verifiedToken = await jwtVerify(userToken, parsedToken);

      if (JSON.stringify(verifiedToken.payload) === JSON.stringify(decodedToken.payload)) {
        // Check the method, path and origin of the verified PoP token
        const checkMethod = verifiedToken.payload.m === req.method ? true : false;
        const checkHost = verifiedToken.payload.u.includes(req.hostname) ? true : false;
        const checkPath = verifiedToken.payload.p.includes(`${req.baseUrl}${req.path}`) ? true : false;

        // If verified, attach the enveloped access token back to the request auth header as a bearer token,
        // and let the passport-azure-ad verify the access token down the line
        if (checkMethod && checkHost && checkPath) {
          req.headers.authorization = 'Bearer ' + verifiedToken.payload.at;
          return next();
        } else {
          return res.status(401).json({ message: 'Invalid token claims' });
        }
      }
    } catch (error) {
      console.error(error);
      res.status(401).json(error);
    }
  } catch (error) {
    console.error(error);
    res.status(401).json(error);
  }
};

More information

For more information about how OAuth 2.0 protocols work in this scenario and other scenarios, see Authentication Scenarios for Azure AD.

About

React SPA calling web API using Proof of Possession


Languages

Language:JavaScript 55.7%Language:PowerShell 39.4%Language:HTML 3.2%Language:CSS 1.7%