Редактиране

Споделяне чрез


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

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

  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

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:

  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 the APIs my organization uses tab.

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

  6. Select Delegated permissions option.

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

  8. 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:

    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.

  9. 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}.

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.