Skip to content

Latest commit

 

History

History

5-Call-MSGraph-ManagedIdentity

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 

README.md

topic sample
languages
csharp
products
microsoft-entra-id
dotnet
office-ms-graph
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

Build status

About this sample

Overview

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).

Scenario

The console application:

  1. Gets a token from Microsoft Entra ID for itself (without a user).
  2. It then calls the Microsoft Graph /users endpoint to get the list of users, of which it displays the count on the screen.

How to run this sample

To run this sample, you'll need:

Step 1: Clone or download this repository into your VM

From the shell or command line in the VM type:

git clone https://github.com/Azure-Samples/active-directory-dotnetcore-daemon-v2.git

or 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"

Step 2: Register the sample with your Entra ID tenant

Choose the Entra ID tenant where your VM is located

As a first step you'll need to:

  1. Sign in to the Microsoft Entra admin center using either a work or school account or a personal Microsoft account.
  2. If your account is present in more than one Microsoft Entra tenant, select Directory + Subscription at the top right corner in the menu on top of the page, and switch your portal session to the desired Microsoft Entra tenant.
  3. In the left-hand navigation pane, select the Microsoft Entra ID service, and then select Managed Identities.

Register the managed identity (daemon-console)

  1. 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.

  2. take note of the identifier of the managed identity you have configured.

Step 3: Configure the sample to use your Entra ID tenant

Open the solution in Visual Studio to configure the projects

Configure the client project

  1. Open the Daemon-Console\Program.cs file
  2. 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.
  3. 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 UserAssignedClientId member in Program.cs, uncomment the line, and replace the existing value with the Client ID of your user-assigned managed identity.

Step 4: Run the sample

In the VM's console, start the client app

cd daemon-console
dotnet run

Consider taking a moment to share your experience with us.

About the code

  1. 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.

  2. 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

Troubleshooting

Did you forget to let the graph API accept your managed identity?

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>"
    }
  }
}

Community Help and Support

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.

Contributing

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.

More information

For more information, see MSAL.NET's conceptual documentation:

For more information about the underlying protocol: