Skip to content

Latest commit

 

History

History
222 lines (157 loc) · 14.9 KB

File metadata and controls

222 lines (157 loc) · 14.9 KB

A Node.js & Express web app calling Microsoft Graph using MSAL Node

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

Overview

This sample demonstrates a Node.js & Express web application that authenticates users against Microsoft Entra ID (Microsoft Entra ID) 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

Scenario

  1. The client application uses MSAL Node (via msal-node-wrapper) to sign-in a user and obtain a JWT Access Token from Microsoft Entra ID.
  2. The Access Token is used as a bearer token to authorize the user to access the resource server (MS Graph or Azure REST API).
  3. The resource server responds with the resource that the user has access to.

Overview

Contents

File/folder Description
AppCreationScripts/ Contains Powershell scripts to automate app registration.
ReadmeFiles/ Contains illustrations and screenshots.
App/authConfig.js Authentication parameters and settings.
App/app.js Application entry point.
App/utils/graphManager.js Handles calls to Microsoft Graph using Graph JS SDK.

Prerequisites

  • 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 Microsoft Entra ID tenant. For more information, see: How to get a Microsoft Entra tenant
  • A user account in your Microsoft Entra ID tenant.

Setup

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 Windows, we recommend cloning into a directory near the root of your drive.

Step 2: Install project dependencies

Locate the root of the sample folder. Then:

    cd 2-Authorization/1-call-graph/App
    npm install

Registration

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

  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 client 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:
    • 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.
  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 you 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 (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 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. 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.

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 Access.
    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 client 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 clientId 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 tenantId and replace the existing value with your Microsoft Entra tenant ID.
  4. Find the key clientSecret and replace the existing value with the key you saved during the creation of msal-node-webapp copied from the Microsoft Entra admin center.
  5. Find the key redirectUri and replace the existing value with the Redirect URI for msal-node-webapp. (by default http://localhost:4000/redirect).

ℹ️ For redirectUri, you can simply enter the path component of the URI instead of the full URI. For example, instead of http://localhost:4000/redirect, you can simply enter /redirect. This may come in handy in deployment scenarios.

  1. Open the App/app.js file.
  2. 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.

Running the sample

Locate the root of the sample folder. Then:

    npm start

Explore the sample

  1. Open your browser and navigate to http://localhost:4000.
  2. Click the Sign-in button on the top right corner.
  3. Once you sign in, click on the See my profile button to call Microsoft Graph.
  4. Once you sign in, click on the Get my tenant button to call Azure Resource Manager.

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.

More information

Configure your application:

Learn more about the Microsoft identity platform:

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

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