Skip to content

Latest commit

 

History

History
280 lines (201 loc) · 17.4 KB

File metadata and controls

280 lines (201 loc) · 17.4 KB
page_type name description languages products urlFragment extensions
sample
A Node.js & Express web app authenticating users against Azure AD for Customers with MSAL Node
This sample demonstrates a Node.js & Express web app authenticating users against Azure Active Directory Customer Identity Access Management (Azure AD for Customers) with Microsoft Authentication Library for Node (MSAL Node)
javascript
entra-external-id
msal-node
ms-identity-ciam-javascript-tutorial-5-sign-in-express
services platform endpoint level client service
ms-identity
JavaScript
AAD v2.0
100
Node.js & Express web app

A Node.js & Express web app authenticating users against Azure AD for Customers with MSAL Node

Overview

This sample demonstrates a Node.js & Express web app that lets users sign-in with Azure Active Directory Consumers Identity and Access Management (Azure AD for Customers) using the Microsoft Authentication Library for Node (MSAL Node).

Here you'll learn about ID Tokens, OIDC scopes, single-sign on, silent requests and more.

Scenario

  1. The client Node.js & Express web app uses the to sign-in a user and obtain a JWT ID Token from Azure AD for Customers.
  2. The ID Token proves that the user has successfully authenticated against Azure AD for Customers.

Scenario Image

Contents

File/folder Description
App/app.js Application entry point.
App/authConfig.js Contains authentication parameters.
App/auth/AuthProvider.js Main authentication logic resides here.

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-ciam-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

    cd 1-Authentication\5-sign-in-express\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 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.

  1. Ensure that you have PowerShell 7 or later installed.

  2. Run the script to create your Azure AD 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 an Azure AD application with certificates. See: How to use certificates instead of client secrets

Choose the Azure AD for Customers 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 Azure portal.
  2. If your account is present in more than one Azure AD for Customers 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 for Customers tenant.

Create User Flows

Please refer to: Tutorial: Create user flow in Azure Active Directory CIAM

ℹ️ To enable password reset in Customer Identity Access Management (CIAM) in Azure Active Directory (Azure AD), please refer to: Tutorial: Enable self-service password reset

Add External Identity Providers

Please refer to:

Register the client app (ciam-msal-node-webapp)

  1. Navigate to the Azure portal and select the Azure AD for Customers 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 ciam-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 and Directory (tenant) ID*. You use these values 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:3000/
      2. http://localhost:3000/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 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.

  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 openid, offline_access in the list. Use the search box if necessary.
    6. Select the Add permissions button at the bottom.
  10. At this stage, the permissions are assigned correctly, but since it's a CIAM tenant, the users themselves cannot consent to these permissions. To get around this problem, we'd let the tenant administrator consent on behalf of all users in the tenant. Select the Grant admin consent for {tenant} button, and then select Yes when you are asked if you want to grant consent for the requested permissions for all accounts in the tenant. You need to be a tenant admin to be able to carry out this operation.
Configure the client app (ciam-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 ciam-msal-node-webapp app copied from the Azure portal.
  3. Find the placeholder Enter_the_Tenant_Subdomain_Here and replace it with the Directory (tenant) subdomain. For instance, if your tenant primary domain is contoso.onmicrosoft.com, use contoso. If you don't have your tenant domain name, learn how to read your tenant details.
  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 ciam-msal-node-webapp copied from the Azure portal.

Step 4: Running the sample

    cd 1-Authentication\5-sign-in-express\App
    npm start

Explore the sample

  1. Open your browser and navigate to http://localhost:3000.
  2. Select the Sign In link.
  3. Select the View ID token claims link to see the claims in your ID token.

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 [azure-active-directory-b2c node ms-identity adal msal-js msal].

To provide feedback on or suggest features for Azure Active Directory, visit User Voice page.

About the code

Initialization

// Explain how the app is configured

Sign-in

// Explain how the app signs in users

Sign-out

To sing-out the current user, the app destroys the session that holds user data and navigates the browser to the Azure AD logout endpoint to end the session with Azure AD. This is shown in auth.js:

Deploying Web app to Azure App Service

There is one web app in this sample. To deploy it to Azure App Services, you'll need to:

  • create an Azure App Service
  • publish the projects to the App Services, and
  • update its client(s) to call the website instead of the local environment.

ℹ️ If you would like to use VS Code Azure Tools extension for deployment, watch the tutorial offered by Microsoft Docs.

Deploy your files (ciam-msal-node-webapp)

  1. In the VS Code activity bar, select the Azure logo to show the Azure App Service explorer. Select Sign in to Azure... and follow the instructions. Once signed in, the explorer should show the name of your Azure subscription(s).
  2. On the App Service explorer section you will see an upward-facing arrow icon. Click on it publish your local files in the project folder to Azure App Services (use "Browse" option if needed, and locate the right folder).
  3. Choose a creation option based on the operating system to which you want to deploy. in this sample, we choose Linux.
  4. Select a Node.js version when prompted. An LTS version is recommended.
  5. Type a globally unique name for your web app and press Enter. The name must be unique across all of Azure. (e.g. ciam-msal-node-webapp)
  6. After you respond to all the prompts, VS Code shows the Azure resources that are being created for your app in its notification popup.
  7. Select Yes when prompted to update your configuration to run npm install on the target Linux server.

Update the CIAM app registration (ciam-msal-node-webapp)

  1. Navigate back to to the Azure portal. In the left-hand navigation pane, select the Azure Active Directory service, and then select App registrations (Preview).
  2. In the resulting screen, select the ciam-msal-node-webapp application.
  3. In the app's registration screen, select Authentication in the menu.
    1. In the Redirect URIs section, update the reply URLs to match the site URL of your Azure deployment. For example:
      1. https://ciam-msal-node-webapp.azurewebsites.net
      2. https://ciam-msal-node-webapp.azurewebsites.net/auth/redirect

⚠️ If your app is using an in-memory storage, Azure App Services will spin down your web site if it is inactive, and any records that your app was keeping will be empty. In addition, if you increase the instance count of your website, requests will be distributed among the instances. Your app's records, therefore, will not be the same on each instance.

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.

Learn More