In this article, let’s create a .NET console application to authenticate using Microsoft Entra ID and request access token. In this example, Microsoft Graph API is used to retrieve the user profile information and display it. Using Microsoft Graph applications one can use Profile API to retrieve profile details of signed in user or another user having a valid Microsoft Entra ID or Microsoft account. Such details in the application can be used for specific purpose or can also be used within Microsoft 365. After this exercise one will be able to configure permissions and interact with the Microsoft Graph in Azure.

Following tasks are performed:

Prerequisites

Before start to retrieve user profile information with Microsoft Graph following things are required:

Register application with Microsoft identity platform

This step is more similar as mentioned in previous article How to Implement Interactive Authentication with MSAL .NET in Azure?

Create .NET console application to send and retrieve message

Next task is to create and set up one .NET console app to send and receive message using GraphServiceClient implementation as mentioned in following steps:

Create console application

First step is to create the console application in local environment using following step:

dotnet new console

Configure application

First add the required packages and after that create and update .env file. env file used to hold the secrets.

dotnet add package Azure.Identity 
dotnet add package Microsoft.Graph 
dotnet add package dotenv.net 
touch .env
code .env
CLIENT_ID="YOUR_CLIENT_ID"
TENANT_ID="YOUR_TENANT_ID"

This step is almost same as mentioned in previous article How to Implement Interactive Authentication with MSAL .NET in Azure?

Starter Code

Add the below starter code into the application. Replace the template code in Program.cs file through editor in Cloud Shell.

code Program.cs
using Azure.Identity;
using Microsoft.Graph;
using dotenv.net;

// Loading environment variables from .env file
DotEnv.Load();

var envVars = DotEnv.Read();
string clientID = envVars["CLIENT_ID"];
string tenantID = envVars["TENANT_ID"];

// Verifying required environment variables
if (string.IsNullOrEmpty(clientID) || string.IsNullOrEmpty(tenantID))
{
    Console.WriteLine("CLIENT_ID and TENANT_ID environment variables are not set. Press any key to continue!");
    Console.ReadLine();
    return;
}

// DEFINE SCOPE - CONFIGURE AUTHENTICATION

// CREATE GRAPH CLIENT - RETRIEVE USER PROFILE

Complete Code

In this section, first code part defines scopes and authentication configuration and second part creates graph client to retrieve user’s profile. Let’s complete the code and update the code for commented lines for the specific operations one by one with description.

// Define Scopes
var scopes = new[] { "User.Read" };

// Configure Authentication
var interactiveBrowserCredentialOptions = new InteractiveBrowserCredentialOptions
{
    ClientID = clientID,
    TenantID = tenantID,
    RedirectURI = new Uri("http://localhost")
};

var interactiveBrowserCredential = new InteractiveBrowserCredential(interactiveBrowserCredentialOptions);
// Create Microsoft Graph client
var gGraphServiceClient = new GraphServiceClient(interactiveBrowserCredential);

// Retrieve user profile
Console.WriteLine("Retrieve user profile!");
Console.ReadLine();
await GetUserProfile(gGraphServiceClient);

// Get and print user profile information
async Task GetUserProfile(GraphServiceClient gGraphServiceClient)
{
    try
    {
        var me = await gGraphServiceClient.Me.GetAsync();

        Console.WriteLine($"User ID : {me?.Id}");
        Console.WriteLine($"Display Name : {me?.DisplayName}");
        Console.WriteLine($"Principal Name : {me?.UserPrincipalName}");

        Console.ReadLine();
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Error message: {ex.Message}");// Write error
        Console.ReadLine();
    }
}

Now it’s time save all the changes and close the modified file by pressing Ctrl + s to save file and then Ctrl + q to exit the editor. Complete code of the Program.cs file is attached with this article.

Run application

Now application is complete and next task is to run the application to validate the results.

dotnet run
Retrieve user profile!
User Id : 7C2....
Display Name : …
Principal Name : …

Clean up resources

Once finished the exercise it’s recommended to delete cloud resources are being created to avoid the unnecessary resource usage and any future costs. Deleting a resource group will delete all resources contained within it. Perform following steps one by one in to Azure Portal to achieve this:

Summary

A complete process flow is described to retrieve user profile information with Microsoft Graph in Azure. First, registered the application using Microsoft identity platform and created a .NET console application. Then, InteractiveBrowserCredential is used to create it’s instance for user profile retrieval. GraphServiceClient is created to get the user profile details using GetUserProfile. Last, application is executed using dotnet run and clean up created resources. Now, one will be able to configure permissions and interact with the Microsoft Graph.