Sign in users and call an API in sample Node.js web application

This guide uses a sample Node.js web application to show you how to add authentication and authorization. The sample application sign in users to a Node.js web app, which then calls a .NET API. You enable authentication and authorization by using your external tenant details. The sample web application uses Microsoft Authentication Library (MSAL) for Node to handle authentication.

In this article, you complete the following tasks:

  • Register and configure a web API in the Microsoft Entra admin center.

  • Register and configure a client web application in the Microsoft Entra admin center.

  • Create a sign-up and sign-in user flow in the Microsoft Entra admin center, and then associate a client web app with it.

  • Update a sample Node web application and ASP.NET web API to use your external tenant details.

  • Run and test the sample web application and API.

Prerequisites

Register a web application and a web API

In this step, you create the web and the web API application registrations, and you specify the scopes of your web API.

Register a web API application

  1. Sign in to the Microsoft Entra admin center as at least an Application Developer.

  2. If you have access to multiple tenants, use the Settings icon in the top menu to switch to your external tenant from the Directories + subscriptions menu.

  3. Browse to Identity > Applications > App registrations.

  4. Select + New registration.

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

    2. Under Supported account types, select Accounts in this organizational directory only.

  6. Select Register to create the application.

  7. The application's Overview pane is displayed when registration is complete. Record the Directory (tenant) ID and the Application (client) ID to be used in your application source code.

Configure API scopes

This API needs to expose permissions, which a client needs to acquire for calling the API:

An API needs to publish a minimum of one scope, also called Delegated Permission, for the client apps to obtain an access token for a user successfully. To publish a scope, follow these steps:

  1. From the App registrations page, select the API application that you created (ciam-ToDoList-api) to open its Overview page.

  2. Under Manage, select Expose an API.

  3. At the top of the page, next to Application ID URI, select the Add link to generate a URI that is unique for this app.

  4. Accept the proposed Application ID URI such as api://{clientId}, and select Save. When your web application requests an access token for the web API, it adds the URI as the prefix for each scope that you define for the API.

  5. Under Scopes defined by this API, select Add a scope.

  6. Enter the following values that define a read access to the API, then select Add scope to save your changes:

    Property Value
    Scope name ToDoList.Read
    Who can consent Admins only
    Admin consent display name Read users ToDo list using the 'TodoListApi'
    Admin consent description Allow the app to read the user's ToDo list using the 'TodoListApi'.
    State Enabled
  7. Select Add a scope again, and enter the following values that define a read and write access scope to the API. Select Add scope to save your changes:

    Property Value
    Scope name ToDoList.ReadWrite
    Who can consent Admins only
    Admin consent display name Read and write users ToDo list using the 'ToDoListApi'
    Admin consent description Allow the app to read and write the user's ToDo list using the 'ToDoListApi'
    State Enabled
  8. Under Manage, select Manifest to open the API manifest editor.

  9. Set accessTokenAcceptedVersion property to 2.

  10. Select Save.

Learn more about the principle of least privilege when publishing permissions for a web API.

Configure app roles

An API needs to publish a minimum of one app role for applications, also called Application Permission, for the client apps to obtain an access token as themselves. Application permissions are the type of permissions that APIs should publish when they want to enable client applications to successfully authenticate as themselves and not need to sign-in users. To publish an application permission, follow these steps:

  1. From the App registrations page, select the application that you created (such as ciam-ToDoList-api) to open its Overview page.

  2. Under Manage, select App roles.

  3. Select Create app role, then enter the following values, then select Apply to save your changes:

    Property Value
    Display name ToDoList.Read.All
    Allowed member types Applications
    Value ToDoList.Read.All
    Description Allow the app to read every user's ToDo list using the 'TodoListApi'
  4. Select Create app role again, then enter the following values for the second app role, then select Apply to save your changes:

    Property Value
    Display name ToDoList.ReadWrite.All
    Allowed member types Applications
    Value ToDoList.ReadWrite.All
    Description Allow the app to read and write every user's ToDo list using the 'ToDoListApi'

Configure optional claims

Tokens returned by Microsoft identity are kept smaller to ensure optimal performance by clients that request them. As a result, several claims are no longer present in the token by default and must be asked for specifically on a per-application basis. For this app, you include idtyp optional claim to help the web API to determine if a token is an app token or an app+user token. Although you can use a combination of scp and roles claims for the same purpose, the use of the idtyp claim is the easiest way to tell an app token and an app+user token apart. For example, the value of this claim is app when the token is an app-only token.

Use the following steps to configure idtyp optional claim:

  1. From the App registrations page, for which you want to configure optional claim, such as ciam-client-app, to open its Overview page.

  2. Under Manage, select Token configuration.

  3. Select Add optional claim.

  4. Under Token type, choose Access.

  5. Select the optional claim idtyp.

  6. Select Add to save your changes.

Register the web app

To enable your application to sign in users with Microsoft Entra, Microsoft Entra External ID must be made aware of the application you create. The app registration establishes a trust relationship between the app and Microsoft Entra. When you register an application, External ID generates a unique identifier known as an Application (client) ID, a value used to identify your app when creating authentication requests.

The following steps show you how to register your app in the Microsoft Entra admin center:

  1. Sign in to the Microsoft Entra admin center as at least an Application Developer.

  2. If you have access to multiple tenants, use the Settings icon in the top menu to switch to your external tenant from the Directories + subscriptions menu.

  3. Browse to Identity >Applications > App registrations.

  4. Select + New registration.

  5. In the Register an application page that appears;

    1. Enter a meaningful application Name that is displayed to users of the app, for example ciam-client-app.
    2. Under Supported account types, select Accounts in this organizational directory only.
  6. Select Register.

  7. The application's Overview pane displays upon successful registration. Record the Application (client) ID to be used in your application source code.

To specify your app type to your app registration, follow these steps:

  1. Under Manage, select Authentication.
  2. On the Platform configurations page, select Add a platform, and then select Web option.
  3. For the Redirect URIs enter http://localhost:3000/auth/redirect.
  4. Select Configure to save your changes.

Create a client secret

Create a client secret for the registered application. The application uses the client secret to prove its identity when it requests for tokens.

  1. From the App registrations page, select the application that you created (such as ciam-client-app) to open its Overview page.
  2. Under Manage, select Certificates & secrets.
  3. Select New client secret.
  4. In the Description box, enter a description for the client secret (for example, ciam app client secret).
  5. Under Expires, select a duration for which the secret is valid (per your organizations security rules), and then select Add.
  6. Record the secret's Value. You'll use this value for configuration in a later step. The secret value won't be displayed again, and isn't retrievable by any means, after you navigate away from the Certificates and secrets. Make sure you record it.

Grant API permissions to the web app

To grant your client app (ciam-client-app) API permissions, follow these steps:

  1. From the App registrations page, select the application that you created (such as ciam-client-app) to open its Overview page.

  2. Under Manage, select API permissions.

  3. Under Configured permissions, select Add a permission.

  4. Select Microsoft APIs tab.

  5. Under Commonly used Microsoft APIs section, select Microsoft Graph.

  6. Select Delegated permissions option.

  7. Under Select permissions section, search for and select both openid and offline_access permissions.

  8. Select Add permissions button.

  9. Under Configured permissions, select Add a permission again.

  10. Select the APIs my organization uses tab.

  11. In the list of APIs, select the API such as ciam-ToDoList-api.

  12. Select Delegated permissions option.

  13. From the permissions list, select ToDoList.Read, ToDoList.ReadWrite (use the search box if necessary).

  14. Select the Add permissions button.

  15. At this point, you've assigned the permissions correctly. However, since the tenant is a customer's tenant, the consumer users themselves can't consent to these permissions. To address this problem, you as the admin must consent to these permissions on behalf of all the users in the tenant:

    1. Select Grant admin consent for <your tenant name>, then select Yes.

    2. Select Refresh, then verify that Granted for <your tenant name> appears under Status for both scopes.

  16. From the Configured permissions list, select the ToDoList.Read and ToDoList.ReadWrite permissions, one at a time, and then copy the permission's full URI for later use. The full permission URI looks something similar to api://{clientId}/{ToDoList.Read} or api://{clientId}/{ToDoList.ReadWrite}.

Create a user flow

Follow these steps to create a user flow a customer can use to sign in or sign up for an application.

  1. Sign in to the Microsoft Entra admin center as at least an External ID User Flow Administrator.

  2. If you have access to multiple tenants, use the Settings icon in the top menu to switch to your external tenant from the Directories + subscriptions menu.

  3. Browse to Identity > External Identities > User flows.

  4. Select + New user flow.

  5. On the Create page:

    1. Enter a Name for the user flow, such as SignInSignUpSample.

    2. In the Identity providers list, select Email Accounts. This identity provider allows users to sign-in or sign-up using their email address.

      Note

      Additional identity providers will be listed here only after you set up federation with them. For example, if you set up federation with Google or Facebook, you'll be able to select those additional identity providers here.

    3. Under Email accounts, you can select one of the two options. For this tutorial, select Email with password.

      • Email with password: Allows new users to sign up and sign in using an email address as the sign-in name and a password as their first factor credential.
      • Email one-time-passcode: Allows new users to sign up and sign in using an email address as the sign-in name and email one-time passcode as their first factor credential. Email one-time passcode must be enabled at the tenant level (All Identity Providers > Email One-time-passcode) for this option to be available at the user flow level.
    4. Under User attributes, choose the attributes you want to collect from the user upon sign-up. By selecting Show more, you can choose attributes and claims for Country/Region, Display Name, and Postal Code. Select OK. (Users are only prompted for attributes when they sign up for the first time.)

  6. Select Create. The new user flow appears in the User flows list. If necessary, refresh the page.

To enable self-service password reset, use the steps in Enable self-service password reset article.

Associate web application with the user flow

Although many applications can be associated with your user flow, a single application can only be associated with one user flow. A user flow allows configuration of the user experience for specific applications. For example, you can configure a user flow that requires users to sign in or sign up with email address.

  1. On the sidebar menu, select Identity.

  2. Select External Identities, then User flows.

  3. In the User flows page, select the User flow name you created earlier, for example, SignInSignUpSample.

  4. Under Use, select Applications.

  5. Select Add application.

  6. Select the application from the list such as ciam-client-app or use the search box to find the application, and then select it.

  7. Choose Select.

Clone or download sample web application and web API

To obtain the sample application, you can either clone it from GitHub or download it as a .zip file.

  • To clone the sample, open a command prompt and navigate to where you wish to create the project, and enter the following command:

    git clone https://github.com/Azure-Samples/ms-identity-ciam-javascript-tutorial.git
    
  • Download the .zip file. Extract it to a file path where the length of the name is fewer than 260 characters.

Install project dependencies

  1. Open a console window, and change to the directory that contains the Node.js/Express sample app:

    cd 2-Authorization\4-call-api-express\App
    
  2. Run the following commands to install web app dependencies:

    npm install && npm update
    

Configure the sample web app and API

To use your app registration in the client web app sample:

  1. In your code editor, open App\authConfig.js file.

  2. Find the placeholder:

    • Enter_the_Application_Id_Here and replace it with the Application (client) ID of the app you registered earlier.
    • Enter_the_Tenant_Subdomain_Here and replace it with the Directory (tenant) subdomain. For example, if your tenant primary domain is contoso.onmicrosoft.com, use contoso. If you don't have your tenant name, learn how to read your tenant details.
    • Enter_the_Client_Secret_Here and replace it with the app secret value you copied earlier.
    • Enter_the_Web_Api_Application_Id_Here and replace it with the Application (client) ID of the web API you copied earlier.

To use your app registration in the web API sample:

  1. In your code editor, open API\ToDoListAPI\appsettings.json file.

  2. Find the placeholder:

    • Enter_the_Application_Id_Here and replace it with the Application (client) ID of the web API you copied.
    • Enter_the_Tenant_Id_Here and replace it with the Directory (tenant) ID you copied earlier.
    • Enter_the_Tenant_Subdomain_Here and replace it with the Directory (tenant) subdomain. For example, if your tenant primary domain is contoso.onmicrosoft.com, use contoso. If you don't have your tenant name, learn how to read your tenant details.

Run and test sample web app and API

  1. Open a console window, then run the web API by using the following commands:

    cd 2-Authorization\4-call-api-express\API\ToDoListAPI
    dotnet run
    
  2. Run the web app client by using the following commands:

    cd 2-Authorization\4-call-api-express\App
    npm start
    
  3. Open your browser, then go to http://localhost:3000.

  4. Select the Sign In button. You're prompted to sign in.

    Screenshot of sign in into a node web app.

  5. On the sign-in page, type your Email address, select Next, type your Password, then select Sign in. If you don't have an account, select No account? Create one link, which starts the sign-up flow.

  6. If you choose the sign-up option, after filling in your email, one-time passcode, new password and more account details, you complete the whole sign-up flow. You see a page similar to the following screenshot. You see a similar page if you choose the sign-in option.

    Screenshot of sign in into a node web app and call an API.

Call API

  1. To call the API, select the View your todolist link. You see a page similar to the following screenshot.

    Screenshot of manipulate API to do list.

  2. Manipulate the to-do list by creating and removing items.

How it works

You trigger an API call each time you view, add, or remove a task. Each time you trigger an API call, the client web app acquires an access token with the required permissions (scopes) to call an API endpoint. For example, to read a task, the client web app must acquire an access token with ToDoList.Read permission/scope.

The web API endpoint needs to check if the permissions or scopes in the access token, provided by the client app, are valid. If the access token is valid, the endpoint responds to the HTTP request, otherwise, it responds with a 401 Unauthorized HTTP error.