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:
Register application using Microsoft identity platform.
Create .NET console application and configure authentication.
Retrieve and display user profile details.
Run application.
Clean up resources.
Prerequisites
Before start to retrieve user profile information with Microsoft Graph following things are required:
Register application with Microsoft identity platform
Login to Azure Portal through the browser.
Navigate to App registrations either from search menu or using navigation panel.
In search box search for App registrations and select it.
From left navigation panel, select Identity than select Applications and than select App Registration
Choose + New registration,
Register application - provide application details in application registration page:
Name: Enter proper application name such as myGraphApplication1 and this will be visible to the user
Supported account types: Select one of the option for who can use the application. Choose “Accounts in this organizational directory only” option. There are following three options are available:
Accounts in this organizational directory only
Accounts in any organizational directory (Any Microsoft Entra ID tenant) - Multitenant
Accounts in any organizational directory (Any Microsoft Entra ID tenant) and personal Microsoft accounts (e.g. Skype, Xbox)
Redirect URI: This is optional parameter. First choose “Public client/native (mobile & desktop)” and then enter “https://localhost:8080” in the text-box. It specifies the redirect URI at where Microsoft identity platform will send security tokens after successful authentication.
Choose Register to register the application. Microsoft Entra ID will assign an unique application ID to the app and control will be redirected to application Overview page.
Overview page - there is a section with name Essentials having the Application (client) ID and the Directory (tenant) ID. These information will be used in console application in to the next section.
![Overview page Essentials section]()
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:
Create project folder with named graphapp1.
Start Visual Studio Code and select than File > Open folder... and choose created graphapp1 project folder.
Select New > Terminal to open a terminal.
![New Terminal]()
Create .NET console application - run the dotnet new console command in the VS Code terminal to create a .NET console application as below.
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 graph client and retrieve user profile - Locate // CREATE GRAPH CLIENT - RETRIEVE USER PROFILE comment, then add following code directly beneath comment. Here, GraphServiceClient is created to get the user profile details using GetUserProfile.
// 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
Application will be open default browser and it will prompt to select account for the authenticate.
First time authentication is required for the registered application as receive “Permissions requested” notification confirm to approve application to be sign in and to allow access to data given it access by selecting Accept.
![Permissions requested notification]()
Console will output result as like below.
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:
Navigate to resource group which is being created here and view it’s contents.
Delete resource group selection from the toolbar.
Choose resource group name and then follow next directions to delete resource group and all the resources it contains.
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.