Sign in users and call a web API in sample Node.js web application
This guide uses a code sample to show you how to add authentication and authorization in a Node.js web application. 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.
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
- Complete the steps in Sign in users and call an API in sample Node.js web application article. This article shows you how to sign in users by using a sample Node.js web app.
- Visual Studio Code or another code editor.
- Node.js.
- .NET 7.0 or later.
- An external tenant. To create one, choose from the following methods:
- (Recommended) Use the Microsoft Entra External ID extension to set up an external tenant directly in Visual Studio Code.
- Create a new external tenant in the Microsoft Entra admin center.
Register 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
Sign in to the Microsoft Entra admin center as at least an Application Developer.
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.
Browse to Identity > Applications > App registrations.
Select + New registration.
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 ciam-ToDoList-api.
Under Supported account types, select Accounts in this organizational directory only.
Select Register to create the application.
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:
From the App registrations page, select the API application that you created (ciam-ToDoList-api) to open its Overview page.
Under Manage, select Expose an API.
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.
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.Under Scopes defined by this API, select Add a scope.
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 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 Under Manage, select Manifest to open the API manifest editor.
Set
accessTokenAcceptedVersion
property to2
.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:
From the App registrations page, select the application that you created (such as ciam-ToDoList-api) to open its Overview page.
Under Manage, select App roles.
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' 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
You can 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, using 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 steps in Configure optional claims article to add idtyp claim to the access token:
- For the Token type select Access.
- From the optional claims list, select idtyp.
Grant API permissions to the web app
To grant your client app (ciam-client-app) API permissions, follow these steps:
From the App registrations page, select the application that you created (such as ciam-client-app) to open its Overview page.
Under Manage, select API permissions.
Under Configured permissions, select Add a permission.
Select the APIs my organization uses tab.
In the list of APIs, select the API such as ciam-ToDoList-api.
Select Delegated permissions option.
From the permissions list, select ToDoList.Read, ToDoList.ReadWrite (use the search box if necessary).
Select the Add permissions button. 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:
Select Grant admin consent for <your tenant name>, then select Yes.
Select Refresh, then verify that Granted for <your tenant name> appears under Status for both scopes.
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}
orapi://{clientId}/{ToDoList.ReadWrite}
.
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
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
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:
In your code editor, open
App\authConfig.js
file.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 iscontoso.onmicrosoft.com
, usecontoso
. 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:
In your code editor, open
API\ToDoListAPI\appsettings.json
file.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 iscontoso.onmicrosoft.com
, usecontoso
. If you don't have your tenant name, learn how to read your tenant details.
Run and test sample web app and API
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
Run the web app client by using the following commands:
cd 2-Authorization\4-call-api-express\App npm start
Open your browser, then go to http://localhost:3000.
Select the Sign In button. You're prompted to sign in.
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.
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.
Call API
To call the API, select the View your todolist link. You see a page similar to the following screenshot.
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.