Изменить

Поделиться через


Quickstart: Call a web API in a sample daemon app

In this quickstart, you use a sample daemon application to acquire an access token and call a protected web API by using the Microsoft Authentication Library (MSAL).

Before you begin, use the Choose a tenant type selector at the top of this page to select tenant type. Microsoft Entra ID provides two tenant configurations, workforce and external. A workforce tenant configuration is for your employees, internal apps, and other organizational resources. An external tenant is for your customer-facing apps.

The sample app you use in this quickstart acquires an access token to call Microsoft Graph API.

Prerequisites

  • An Azure account with an active subscription. If you don't already have one, Create an account for free.
  • This Azure account must have permissions to manage applications. Any of the following Microsoft Entra roles include the required permissions:
    • Application Administrator
    • Application Developer
    • Cloud Application Administrator
  • A workforce tenant. You can use your Default Directory or set up a new tenant.
  • Register a new app in the Microsoft Entra admin center with the following configuration. For more information, see Register an application.
    • Name: identity-client-daemon-app
    • Supported account types: Accounts in this organizational directory only (Single tenant)

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 web app client secret) to open its Overview page.
  2. Under Manage, select Certificates & secrets > Client secrets > New client secret.
  3. In the Description box, enter a description for the client secret (for example, web app client secret).
  4. Under Expires, select a duration for which the secret is valid (per your organizations security rules), and then select Add.
  5. Record the secret's Value. You 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.

When you create credentials for a confidential client application:

  • Microsoft recommends that you use a certificate instead of a client secret before moving the application to a production environment. For more information on how to use a certificate, see instructions in Microsoft identity platform application authentication certificate credentials.

  • For testing purposes, you can create a self-signed certificate and configure your apps to authenticate with it. However, in production, you should purchase a certificate signed by a well-known certificate authority, then use Azure Key Vault to manage certificate access and lifetime.

Grant API permissions to the daemon app

For daemon app to access data in Microsoft Graph API, you grant it the permissions it needs. The daemon app needs application type permissions. Users can't interact with a daemon application, so the tenant administrator must consent to these permissions. Use the following steps to grant and consent to the permissions:

For the .NET daemon app, you don't need to grant and consent to any permission. This daemon app reads its own app registration information, so it can do so without being granted any application permissions.

Clone or download the sample application

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-docs-code-dotnet.git
  • Download the .zip file. Extract it to a file path where the length of the name is fewer than 260 characters.

Configure the project

To use your app registration details in the client daemon app sample, use the following steps:

  1. Open a console window then navigate to the ms-identity-docs-code-dotnet/console-daemon directory:

    cd ms-identity-docs-code-dotnet/console-daemon
    
  2. Open Program.cs and replace the file contents with the following snippet;

     // Full directory URL, in the form of https://login.microsoftonline.com/<tenant_id>
     Authority = " https://login.microsoftonline.com/Enter_the_tenant_ID_obtained_from_the_Microsoft_Entra_admin_center",
     // 'Enter the client ID obtained from the Microsoft Entra admin center
     ClientId = "Enter the client ID obtained from the Microsoft Entra admin center",
     // Client secret 'Value' (not its ID) from 'Client secrets' in the Microsoft Entra admin center
     ClientSecret = "Enter the client secret value obtained from the Mifcrosoft Entra admin center",
     // Client 'Object ID' of app registration in Microsoft Entra admin center - this value is a GUID
     ClientObjectId = "Enter the client Object ID obtained from the Microsoft Entra admin center"
    
    • Authority - The authority is a URL that indicates a directory that MSAL can request tokens from. Replace Enter_the_tenant_ID_obtained_from_the_Microsoft_Entra_admin_center with the Directory (tenant) ID value that was recorded earlier.
    • ClientId - The identifier of the application, also referred to as the client. Replace the text in quotes with the Application (client) ID value that was recorded earlier from the overview page of the registered application.
    • ClientSecret - The client secret created for the application in the Microsoft Entra admin center. Enter the value of the client secret.
    • ClientObjectId - The object ID of the client application. Replace the text in quotes with the Object ID value that you recorded earlier from the overview page of the registered application.

Run and test the application

You've configured your sample app. You can proceed to run and test it.

From your console window, run the following command to build and run the application:

dotnet run

Once the application runs successfully, it displays a response similar to the following snippet (shortened for brevity):

{
"@odata.context": "https://graph.microsoft.com/v1.0/$metadata#applications/$entity",
"id": "00001111-aaaa-2222-bbbb-3333cccc4444",
"deletedDateTime": null,
"appId": "00001111-aaaa-2222-bbbb-3333cccc4444",
"applicationTemplateId": null,
"disabledByMicrosoftStatus": null,
"createdDateTime": "2021-01-17T15:30:55Z",
"displayName": "identity-dotnet-console-app",
"description": null,
"groupMembershipClaims": null,
...
}

How it works

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 by presenting its application ID, credential (secret or certificate), and an application ID URI. The daemon application uses the standard OAuth 2.0 client credentials grant flow to acquire an access token.

The app acquires an access token from Microsoft identity platform. The access token is scoped for the Microsoft Graph API. The app then uses the access token to request its own application registration details from Microsoft Graph API. The app can request any resource from Microsoft Graph API as long as the access token has the right permissions.

The sample demonstrates how an unattended job or Windows service can run with an application identity, instead of a user's identity.

Prerequisites

  • An Azure account with an active subscription. If you don't already have one, Create an account for free.
  • This Azure account must have permissions to manage applications. Any of the following Microsoft Entra roles include the required permissions:
    • Application Administrator
    • Application Developer
    • Cloud Application Administrator
  • An external tenant. To create one, choose from the following methods:
  • Register a new app in the Microsoft Entra admin center with the following configuration. For more information, see Register an application.
    • Name: ciam-daemon-app
    • Supported account types: Accounts in this organizational directory only (Single tenant)
  • Visual Studio Code or another code editor.
  • .NET 7.0 or later.
  • Node.js (for Node implementation only)

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 web app client secret) to open its Overview page.
  2. Under Manage, select Certificates & secrets > Client secrets > New client secret.
  3. In the Description box, enter a description for the client secret (for example, web app client secret).
  4. Under Expires, select a duration for which the secret is valid (per your organizations security rules), and then select Add.
  5. Record the secret's Value. You 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.

When you create credentials for a confidential client application:

  • Microsoft recommends that you use a certificate instead of a client secret before moving the application to a production environment. For more information on how to use a certificate, see instructions in Microsoft identity platform application authentication certificate credentials.

  • For testing purposes, you can create a self-signed certificate and configure your apps to authenticate with it. However, in production, you should purchase a certificate signed by a well-known certificate authority, then use Azure Key Vault to manage certificate access and lifetime.

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.

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 add the idtyp optional claim to help the web API to determine whether 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.

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 details in the client web app sample, use the following steps:

  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

You've configured your sample app. You can proceed to run and test it.

  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 the OAuth 2.0 client credentials grant flow 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, a sample .NET web API, the 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.