Call an API in a sample Node.js daemon application

This guide uses a sample Node.js daemon application to show you how a daemon app acquires an access token to call a web API.

A daemon application acquires a token on behalf of itself (not on behalf of a user). Users can't interact with a daemon application because it requires its own identity. This type of application requests an access token by using its application identity and presenting its application ID, credential (password or certificate), and application ID URI to External ID.

A daemon app uses the standard OAuth 2.0 client credentials grant. To simplify the process of acquiring the token, the sample we use in this article uses Microsoft Authentication Library for Node (MSAL Node).

Prerequisites

Register a daemon application and a web API

In this step, you create the daemon 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 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

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.

Register the daemon 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.

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 daemon app

  1. From the App registrations page, select the application that you created, such as ciam-client-app.

  2. Under Manage, select API permissions.

  3. Under Configured permissions, select Add a permission.

  4. Select the APIs my organization uses tab.

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

  6. Select Application permissions option. We select this option as the app signs in as itself, but not on behalf of a user.

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

  8. Select the Add permissions button.

  9. At this point, you've assigned the permissions correctly. However, since the daemon app doesn't allow users to interact with it, the 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 permissions.

Clone or download sample daemon 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
    
  • Alternatively, download the samples .zip file, then 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 sample app:

    cd 2-Authorization\3-call-api-node-daemon\App
    
  2. Run the following commands to install app dependencies:

    npm install && npm update
    

Configure the sample daemon 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 daemon 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 daemon 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 daemon app and API

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

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

    2-Authorization\3-call-api-node-daemon\App
    node . --op getToDos
    
  • If your daemon app and web API successfully run, you should see something similar to the following JSON array in your console window

    {
        "id": 1,
        "owner": "3e8....-db63-43a2-a767-5d7db...",
        "description": "Pick up grocery"
    },
    {
        "id": 2,
        "owner": "c3cc....-c4ec-4531-a197-cb919ed.....",
        "description": "Finish invoice report"
    },
    {
        "id": 3,
        "owner": "a35e....-3b8a-4632-8c4f-ffb840d.....",
        "description": "Water plants"
    }
    

How it works

The Node.js app uses OAuth 2.0 client credentials grant to acquire an access token for itself and not for the user. The access token that the app requests contains the permissions represented as roles. The client credential flow uses this set of permissions in place of user scopes for application tokens. You exposed these application permissions in the web API earlier, then granted them to the daemon app.

On the API side, the web API must verify that the access token has the required permissions (application permissions). The web API can't accept an access token that doesn't have the required permissions.

Access to data

A Web API endpoint should be prepared to accept calls from both users and applications. Therefore, it should have a way to respond to each request accordingly. For example, a call from a user via delegated permissions/scopes receives the user's data to-do list. On the other hand, a call from an application via application permissions/roles may receive the entire to-do list. However, in this article, we're only making an application call, so we didn't need to configure delegated permissions/scopes.