Quickstart: Get a token and call the Microsoft Graph API by using a console app's identity

In this quickstart, you download and run a code sample that demonstrates how a .NET Core console application can get an access token to call the Microsoft Graph API and display a list of users in the directory. The code sample also demonstrates how a job or a Windows service can run with an application identity, instead of a user's identity. The sample console application in this quickstart is also a daemon application, so it's a confidential client application.

The following diagram shows how the sample app works:

Diagram that shows how the sample app generated by this quickstart works.

Prerequisites

This quickstart requires .NET Core 3.1 but will also work with .NET Core 5.0.

Register and download the app

You have two options to start building your application: automatic or manual configuration.

Automatic configuration

If you want to register and automatically configure your app and then download the code sample, follow these steps:

  1. Go to the Azure portal page for app registration.
  2. Enter a name for your application and select Register.
  3. Follow the instructions to download and automatically configure your new application in one click.

Manual configuration

If you want to manually configure your application and code sample, use the following procedures.

Step 1: Register your application

To register your application and add the app's registration information to your solution manually, follow these steps:

  1. Sign in to the Azure portal.
  2. If you have access to multiple tenants, use the Directory + subscription filter on the top menu to select the tenant in which you want to register the application.
  3. Search for and select Azure Active Directory.
  4. Under Manage, select App registrations > New registration.
  5. For Name, enter a name for your application. For example, enter Daemon-console. Users of your app will see this name, and you can change it later.
  6. Select Register to create the application.
  7. Under Manage, select Certificates & secrets.
  8. Under Client secrets, select New client secret, enter a name, and then select Add. Record the secret value in a safe location for use in a later step.
  9. Under Manage, select API Permissions > Add a permission. Select Microsoft Graph.
  10. Select Application permissions.
  11. Under the User node, select User.Read.All, and then select Add permissions.

Download and configure your quickstart app

Step 1: Configure your application in the Azure portal

For the code sample in this quickstart to work, create a client secret and add the Graph API's User.Read.All application permission.

Already configured Your application is configured with these attributes.

Step 2: Download your Visual Studio project

Download the Visual Studio project

You can run the provided project in either Visual Studio or Visual Studio for Mac.

Run the project by using Visual Studio 2019.

Tip

To avoid errors caused by path length limitations in Windows, we recommend extracting the archive or cloning the repository into a directory near the root of your drive.

Note

Enter_the_Supported_Account_Info_Here

Step 3: Configure your Visual Studio project

  1. Extract the .zip file to a local folder that's close to the root of the disk. For example, extract to C:\Azure-Samples.

    We recommend extracting the archive into a directory near the root of your drive to avoid errors caused by path length limitations on Windows.

  2. Open the solution in Visual Studio: 1-Call-MSGraph\daemon-console.sln (optional).

  3. In appsettings.json, replace the values of Tenant, ClientId, and ClientSecret:

    "Tenant": "Enter_the_Tenant_Id_Here",
    "ClientId": "Enter_the_Application_Id_Here",
    "ClientSecret": "Enter_the_Client_Secret_Here"
    

    In that code:

    • Enter_the_Application_Id_Here is the application (client) ID for the application that you registered. To find the values for the application (client) ID and the directory (tenant) ID, go to the app's Overview page in the Azure portal.
    • Replace Enter_the_Tenant_Id_Here with the tenant ID or tenant name (for example, contoso.microsoft.com).
    • Replace Enter_the_Client_Secret_Here with the client secret that you created in step 1. To generate a new key, go to the Certificates & secrets page.

If you try to run the application at this point, you'll receive an HTTP 403 - Forbidden error: "Insufficient privileges to complete the operation." This error happens because any app-only permission requires a global administrator of your directory to give consent to your application. Select one of the following options, depending on your role.

Global tenant administrator

If you're a global tenant administrator, go to Enterprise applications in the Azure portal. Select your app registration, and select Permissions from the Security section of the left pane. Then select the large button labeled Grant admin consent for {Tenant Name} (where {Tenant Name} is the name of your directory).

If you're a global administrator, go to the API Permissions page and select Grant admin consent for Enter_the_Tenant_Name_Here.

Standard user

If you're a standard user of your tenant, ask a global administrator to grant admin consent for your application. To do this, give the following URL to your administrator:

https://login.microsoftonline.com/Enter_the_Tenant_Id_Here/adminconsent?client_id=Enter_the_Application_Id_Here

In that URL:

  • Replace Enter_the_Tenant_Id_Here with the tenant ID or tenant name (for example, contoso.microsoft.com).
  • Enter_the_Application_Id_Here is the application (client) ID for the application that you registered.

You might see the error "AADSTS50011: No reply address is registered for the application" after you grant consent to the app by using the preceding URL. This error happens because this application and the URL don't have a redirect URI. You can ignore it.

Step 4: Run the application

Step 5: Run the application

If you're using Visual Studio or Visual Studio for Mac, press F5 to run the application. Otherwise, run the application via command prompt, console, or terminal:

cd {ProjectFolder}\1-Call-MSGraph\daemon-console
dotnet run

In that code:

  • {ProjectFolder} is the folder where you extracted the .zip file. An example is C:\Azure-Samples\active-directory-dotnetcore-daemon-v2.

You should see a list of users in Azure Active Directory as result.

This quickstart application uses a client secret to identify itself as a confidential client. The client secret is added as a plain-text file to your project files. For security reasons, we recommend that you use a certificate instead of a client secret before considering the application as a production application. For more information on how to use a certificate, see these instructions in the GitHub repository for this sample.

More information

This section gives an overview of the code required to sign in users. This overview can be useful to understand how the code works, what the main arguments are, and how to add sign-in to an existing .NET Core console application.

How the sample works

Diagram that shows how the sample app generated by this quickstart works.

MSAL.NET

Microsoft Authentication Library (MSAL, in the Microsoft.Identity.Client package) is the library that's used to sign in users and request tokens for accessing an API protected by the Microsoft identity platform. This quickstart requests tokens by using the application's own identity instead of delegated permissions. The authentication flow in this case is known as a client credentials OAuth flow. For more information on how to use MSAL.NET with a client credentials flow, see this article.

You can install MSAL.NET by running the following command in the Visual Studio Package Manager Console:

dotnet add package Microsoft.Identity.Client

MSAL initialization

You can add the reference for MSAL by adding the following code:

using Microsoft.Identity.Client;

Then, initialize MSAL by using the following code:

IConfidentialClientApplication app;
app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
                                          .WithClientSecret(config.ClientSecret)
                                          .WithAuthority(new Uri(config.Authority))
                                          .Build();
Element Description
config.ClientSecret The client secret created for the application in the Azure portal.
config.ClientId The application (client) ID for the application registered in the Azure portal. You can find this value on the app's Overview page in the Azure portal.
config.Authority (Optional) The security token service (STS) endpoint for the user to authenticate. It's usually https://login.microsoftonline.com/{tenant} for the public cloud, where {tenant} is the name of your tenant or your tenant ID.

For more information, see the reference documentation for ConfidentialClientApplication.

Requesting tokens

To request a token by using the app's identity, use the AcquireTokenForClient method:

result = await app.AcquireTokenForClient(scopes)
                  .ExecuteAsync();
Element Description
scopes Contains the requested scopes. For confidential clients, this value should use a format similar to {Application ID URI}/.default. This format indicates that the requested scopes are the ones that are statically defined in the app object set in the Azure portal. For Microsoft Graph, {Application ID URI} points to https://graph.microsoft.com. For custom web APIs, {Application ID URI} is defined in the Azure portal, under Application Registration (Preview) > Expose an API.

For more information, see the reference documentation for AcquireTokenForClient.

Help and support

If you need help, want to report an issue, or want to learn about your support options, see Help and support for developers.

Next steps

To learn more about daemon applications, see the scenario overview: