| topic | sample | |||
|---|---|---|---|---|
| languages |
|
|||
| products |
|
|||
| description | Shows how a daemon console app uses a managed identity to get an access token and call Microsoft Graph using the Microsoft.Identity.Web library. |
A .NET Core daemon console application calling a protected Web API with its own identity using Managed identity
This sample application shows how to use the Microsoft identity platform to access the data of Microsoft business customers in Microsoft Graph in a non-interactive process. It uses Managed Identity to acquire an Access Token(s), which is then used to call the Microsoft Graph API and access organizational data.
The app is a .NET Core Console application. It gets the number of users in a Microsoft Entra tenant by using Microsoft.Identity.Web token acquirer, which is a higher level API on top of the Microsoft Authentication Library for .NET (MSAL.NET).
The console application:
- Gets a token from Microsoft Entra ID for itself (without a user).
- It then calls the Microsoft Graph
/usersendpoint to get the list of users, of which it displays the count on the screen.
- Developers who wish to gain good familiarity of programming with Microsoft Graph are advised to go through the An introduction to Microsoft Graph for developers recorded session.
To run this sample, you'll need:
- Visual Studio and the .NET Core SDK
- An Internet connection
- An Entra ID tenant. For more information on how to create an Entra ID tenant, see Get a Microsoft Entra ID tenant.
- An Azure virtual machine (VM) with a configured managed identity. For information on how to set up a VM with a managed identity, follow the instructions in the managed identity article.
From the shell or command line in the VM type:
git clone https://github.com/Azure-Samples/active-directory-dotnetcore-daemon-v2.gitor download and extract the repository .zip file.
Given that the name of the sample is pretty long, and so are the name of the referenced NuGet packages, you might want to clone it in a folder close to the root of your hard drive, to avoid file size limitations on Windows.
Navigate to the "5-Call-MSGraph-ManagedIdentity" folder
cd "5-Call-MSGraph-ManagedIdentity"As a first step you'll need to:
- Sign in to the Microsoft Entra admin center using either a work or school account or a personal Microsoft account.
- If your account is present in more than one Microsoft Entra tenant, select
Directory + Subscriptionat the top right corner in the menu on top of the page, and switch your portal session to the desired Microsoft Entra tenant. - In the left-hand navigation pane, select the Microsoft Entra ID service, and then select Managed Identities.
-
In order to access Microsoft Graph you'll need to grant the correct permissions to your managed identity. To do this follow the instructions in the "Grant access to Microsoft Graph" section of this article.
-
take note of the identifier of the managed identity you have configured.
Open the solution in Visual Studio to configure the projects
- Open the
Daemon-Console\Program.csfile - If you are connecting to a national cloud, change the scope to the correct Microsoft Graph endpoint. See this reference for a list of Microsoft Graph endpoints.
- If you are using a system=assigned managed identity, you don't need to change a thing. If using a user-assigned managed identity, find the
UserAssignedClientIdmember in Program.cs, uncomment the line, and replace the existing value with the Client ID of your user-assigned managed identity.
In the VM's console, start the client app
cd daemon-console
dotnet run-
To learn more about the code specific to using managed identity please see the wiki here. The wiki includes an example of calling Microsoft Graph as well as an additional example of how to call your own API.
-
Call the Microsoft Graph API using the Graph SDK
In that case calling "https://graph.microsoft.com/v1.0/users" with the access token as a bearer token. You get the GraphServiceClient as a required service, and use it to request the list of users in the tenant. Given you are writing a daemon application, use
.WithAppOnly()to get an app-only token.try { GraphServiceClient graphServiceClient = serviceProvider.GetRequiredService<GraphServiceClient>(); var users = await graphServiceClient.Users .GetAsync(r => r.Options.WithAppOnly() .WithAuthenticationOptions(o => { // Specify your target Microsoft Graph endpoint as the scope for the request. o.Scopes = new string[] { "https://graph.microsoft.com/.default" }; // Tell the library to use a managed identity, by default it uses the system-assigned managed identity. o.AcquireTokenOptions.ManagedIdentity = new() { // Uncomment the below line and edit the value to use a user-assigned managed identity. // UserAssignedClientId = "ClientID-of-the-user-assigned-managed-identity" }; }) ); Console.WriteLine($"{users.Value.Count} users"); } catch (ServiceException e) { Console.WriteLine("We could not retrieve the user's list: " + $"{e}"); }
Note that:
- You don't need to define the scopes here. Applications that authenticate as themselves, cannot specify, in the code, the individual scopes that they want to access. The scopes (app permissions) have to be statically declared during the application registration step. Therefore the only possible scope that can be specified in the code is "resource/.default" (here, "https://graph.microsoft.com/.default"). When you use the GraphServiceClient using
WithAppOnly, the scopes are automatically set to "https://graph.microsoft.com/.default" for you. - You don't need either to acquire a token. Microsoft.Identity.Web takes care of acquiring a token for you, and add it to the request made by Microsoft Graph
- You don't need to define the scopes here. Applications that authenticate as themselves, cannot specify, in the code, the individual scopes that they want to access. The scopes (app permissions) have to be statically declared during the application registration step. Therefore the only possible scope that can be specified in the code is "resource/.default" (here, "https://graph.microsoft.com/.default"). When you use the GraphServiceClient using
If you get an error when calling the API Insufficient privileges to complete the operation., this is because the tenant administrator has not granted permissions
to the application. See step 4 of Register the client app (daemon-console-v2) above.
You will typically see, on the output window, something like the following:
Failed to call the Web Api: Forbidden
Content: {
"error": {
"code": "Authorization_RequestDenied",
"message": "Insufficient privileges to complete the operation.",
"innerError": {
"request-id": "<a guid>",
"date": "<date>"
}
}
}Use Stack Overflow to get support from the community.
Ask your questions on Stack Overflow first and browse existing issues to see if someone has asked your question before.
Make sure that your questions or comments are tagged with [msal dotnet].
If you find a bug in the sample, please raise the issue on GitHub Issues.
If you find a bug in Msal.Net, please raise the issue on MSAL.NET GitHub Issues.
To provide a recommendation, visit the following User Voice page.
If you'd like to contribute to this sample, see CONTRIBUTING.MD.
This project has adopted the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.
For more information, see MSAL.NET's conceptual documentation:
- Quickstart: Register an application with the Microsoft identity platform
- Quickstart: Configure a client application to access web APIs
- Acquiring a token for an application with client credential flows
For more information about the underlying protocol: