Skip to content

Latest commit

 

History

History
427 lines (308 loc) · 26.2 KB

File metadata and controls

427 lines (308 loc) · 26.2 KB

On-behalf-of flow and Conditional Access challenges

  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 single-page application (SPA) calling a Node.js web API (DownstreamAPI) protected by a conditional access policy via another web API (MiddletierAPI) using the OAuth 2.0 on-behalf-of (OBO) flow. The SPA project is secured using the Microsoft Authentication Library for React (MSAL React), while the web APIs leverage the passport-azure-ad package.

The downstream web API has a conditional access policy that enables multi-factor authentication (MFA). Thus, the Access Token for the downstream web API will only be issued by Azure AD if the signed-in user has performed MFA. However, since the downstream web API has no user interaction capability, the claims challenge generated by the conditional access policy needs to be propagated back to the client app (SPA) via the middle-tier web API, which can then take the user back to Azure AD to get the MFA done.

Scenario

  1. The client app uses MSAL React to sign-in a user and obtain a JWT Access Token from Azure AD for the middle-tier web API.
  2. The access token is used as a bearer token to authorize the user to call the middle-tier web API protected by the Azure AD.
  3. The middle-tier web API uses the access token sent from the client app to Azure AD to receive a new access token using the OBO flow for the downstream web API. If the user hasn't satisfied the MFA, Azure AD generates a claims challenge and sends the challenge back to the middle-tier web API.
  4. The middle-tier web API propagates the claims challenge back to client app, which then initiates an interactive token request to get the user to perform MFA.
  5. Once the user successfully conducts MFA, a new access token for is provided to client app for the middle-tier web API.
  6. Steps 2 and 3 are repeated, and this time the call to downstream web API succeeds.

Overview

Contents

File/folder Description
AppCreationScripts/ Contains Powershell scripts to automate app registration.
SPA/src/authConfig.js Contains configuration parameters for the SPA.
MiddletierAPI/config.json Contains authentication parameters for the middle-tier API.
DownstreamAPI/config.json Contains authentication parameters for the downstream API.

Prerequisites

  • An Azure AD tenant with Conditional Access available. 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.
  • Make sure that the user account you want to use for this is enabled for MFA.

Setup

Step 1: Clone or download this repository

From your shell or command line:

    git clone https://github.com/Azure-Samples/ms-identity-javascript-tutorial.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 project dependencies

Locate the project root folder in a command prompt. Then:

    cd DownstreamAPI
    npm install
    cd ..
    cd MiddletierAPI
    npm install
    cd ..
    cd SPA
    npm install

Registration

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

There are three 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 downstream web API (msal-react-downstream)

  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-downstream.
    • 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_downstream_api_as_user.
      • Select Admins and users options for Who can consent?.
      • For Admin consent display name type Access msal-react-downstream.
      • For Admin consent description type Allows the app to access msal-react-downstream as the signed-in user.
      • For User consent display name type Access msal-react-downstream.
      • For User consent description type Allow the application to access msal-react-downstream on your behalf.
      • Keep State as Enabled.
      • Select the Add scope button on the bottom to save this scope.
  9. On the right side menu, select the Manifest blade.
    • Set accessTokenAcceptedVersion property to 2.
    • Click on Save.

Configure the downstream web API (msal-react-downstream) 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 DownstreamAPI\config.json file.
  2. Find the key clientID and replace the existing value with the application ID (clientId) of msal-react-downstream app copied from the Azure portal.
  3. Find the key tenantID and replace the existing value with your Azure AD tenant ID.

Register the middle-tier web API (msal-react-middletier)

  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-middletier.
    • 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 Certificates & secrets blade in the left to open the page where we can generate secrets and upload certificates.
  8. 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.
  9. 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-react-downstream.
    • In the Delegated permissions section, select the access_downstream_api_as_user in the list. Use the search box if necessary.
    • Select the Add permissions button at the bottom.
  10. 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.
  11. 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_middletier_api_as_user.
      • Select Admins and users options for Who can consent?.
      • For Admin consent display name type Access msal-react-middletier.
      • For Admin consent description type Allows the app to access msal-react-middletier as the signed-in user.
      • For User consent display name type Access msal-react-middletier.
      • For User consent description type Allow the application to access msal-react-middletier on your behalf.
      • Keep State as Enabled.
      • Select the Add scope button on the bottom to save this scope.
  12. On the right side menu, select the Manifest blade.
    • Set accessTokenAcceptedVersion property to 2.
    • Click on Save.

Configure the middle-tier web API (msal-react-middletier) 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 MiddletierAPI\config.json file.
  2. Find the key clientID and replace the existing value with the application ID (clientId) of msal-react-middletier app copied from the Azure portal.
  3. Find the key tenantID and replace the existing value with your Azure AD tenant ID.
  4. Find the key clientSecret and replace the existing value with the key you saved during the creation of msal-react-middletier copied from the Azure portal.
  5. Find the key downstreamAPI.resourceScopes and replace the existing value with the scope you have exposed during the registration of DownstreamAPI project using the .default form e.g. api://<DownstreamAPI_Application_Id>/.default.

Configure Known Client Applications for the downstream web API (msal-react-downstream)

  1. In the Azure portal, navigate to your msal-react-downstream app registration, and select Manifest section.

  2. In the manifest editor, change the "knownClientApplications": [] line so that the array contains the Client ID of the client application (msal-react-middletier) as an element of the array.

    For instance:

    "knownClientApplications": ["ca8dca8d-f828-4f08-82f5-325e1a1c6428"],
  3. Save the changes to the manifest.

Register the SPA 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-react-middletier.
    • In the Delegated permissions section, select the access_middletier_api_as_user in the list. Use the search box if necessary.
    • Select the Add permissions button at the bottom.

Configure the SPA 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 key Enter_the_Application_Id_Here and replace the existing value with the application ID (clientId) of msal-react-spa app copied from the Azure portal.
  3. Find the key https://login.microsoftonline.com/Enter_the_Tenant_Info_Here and replace the existing value with your tenant ID copied from Azure portal.
  4. Find the key Enter_the_Redirect_Uri_Here and replace the existing value with the Redirect URI for msal-react-spa. (by default http://localhost:3000/).
  5. Find the key Enter_the_Web_Api_Scope_Here and replace the existing value with the scope for msal-react-middletier using the .default form e.g. api://<Enter_Web_API_Application_Id>/.default.

Configure Known Client Applications for the middle-tier web API (msal-react-middletier)

  1. In the Azure portal, navigate to your msal-react-middletier app registration, and select Manifest section.

  2. In the manifest editor, change the "knownClientApplications": [] line so that the array contains the Client ID of the client application (msal-react-spa) as an element of the array.

    For instance:

    "knownClientApplications": ["ca8dca8d-f828-4f08-82f5-325e1a1c6428"],
  3. Save the changes to the manifest.

Enable Conditional Access for the downstream web API

  1. Inside the Azure Active Directory window, select the Conditional Access button near the bottom of the list under Security.

CA1

  1. Select New Policy and name your policy.

CA3

  1. Select the Users and groups button and then select the user account you want to work with in the Include tab (hint: you might want to use a test account for this).

CA4

  1. Select the Cloud apps and actions, then hit the Select apps radio button in the Include tab, and select the msal-react-downstream.

CA5

  1. Finally, select the Grant button and hit Grant access. Then check the Require multi-factor authentication option.

CA6

  1. Enable the policy and save. Access to your web API now requires multi-factor authentication!

Running the sample

Run all three projects. Open 3 separate command prompts, and type:

    cd DownstreamAPI
    npm start
    cd MiddletierAPI
    npm start
    cd SPA
    npm start

Explore the sample

  1. Open your browser and navigate to http://localhost:3000.
  2. Click the sign-in button on the top right corner.
  3. Once you authenticate, click the Call API button at the center, which will result in MFA required screen.

Screenshot

  1. If the user has no predefined verification method to satisfy MFA, they will see the following screen:

More

  1. They will then have to setup a verification method:

Verification

ℹ️ 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.

About the code

Handling conditional access claims challenge

If the conditional access policy is not satisfied when calling the downstream web API, Azure AD will throw an error together with a claims challenge. In our middle-tier web API, we are to catch this and send it to the client SPA. This is illustrated in the middle-tier web API index.js file:

   try {
      // request new token and use it to call resource API on user's behalf
      tokenObj = await getNewAccessToken(userToken);

      // check for errors
      if (tokenObj['error_codes']) {
            
            /**
             * Conditional access MFA requirement throws an AADSTS50076 error.
             * If the user has not enrolled in MFA, an AADSTS50079 error will be thrown instead.
             * If the user has not consented to required scopes, an AADSTS65001 error will be thrown instead.
             * In either case, sample middle-tier API will propagate the error back to the client.
             * For more, visit: https://docs.microsoft.com/azure/active-directory/develop/v2-conditional-access-dev-guide
             */
            if (tokenObj['error_codes'].includes(50076) || tokenObj['error_codes'].includes(50079) || tokenObj['error_codes'].includes(65001)) {
               return res.status(403).json(tokenObj);
            }
      }

      try {
            // access the resource with the token
            let apiResponse = await callResourceAPI(tokenObj['access_token'], config.resources.downstreamAPI.resourceUri);
            return res.status(200).json(apiResponse);
      } catch (error) {
            console.log(error);
            return res.status(403).json(error);
      }
      
   } catch (error) {
      console.log(error);
      return res.status(403).json(error);
   }

Then, in the SPA project, we catch this error response and initiate an interactive token request with additional claims. To do so, we append the JSON object from the response to our tokenRequest object before triggering the interactive token request. This is illustrated in api.js:

   

In the component:

   

More information

Configure your application:

Learn more about Microsoft identity platform:

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

Community Help and Support

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 react ms-identity 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.

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 opencode@microsoft.com with any additional questions or comments.