Azure  

How to Implement Interactive Authentication with MSAL .NET in Azure?

In this article, Microsoft Authentication Library ( MSAL ) is used to implement interactive authentication using MSAL.NET SDK. MSAL.NET is a library for authentication which allows to acquire tokens from the Microsoft Entra ID to access protected web APIs. It is available for various .NET platforms such as web, mobile or desktop applications. Let’s use MSAL to perform interactive authentication and acquire token access for the Microsoft Graph. After this exercise one will be able to configure authentication scope, manage user consent and cache tokens for the subsequent executions.

Following tasks are performed:

  • Register application with Microsoft identity platform.

  • Create .NET console application to configure authentication.

  • Acquire token interactively using Microsoft Graph.

  • Run application

  • Clean up resources

Prerequisites

Following things are required before start to implement interactive authentication with MSAL .NET:

  • Azure Subscription

  • Visual Studio Code

  • .NET 8 target framework

  • C# Dev Kit for Visual Studio Code

    CSharp Dev Kit for Visual Studio Code

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 myMSALApplication1 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

Create .NET console application to configure authentication

Next task is to create one .NET console app to implements a PublicClientApplicationBuilder class which configures authentication.

Create console application

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

  • Create project folder with named myMSALApplication1.

  • Start Visual Studio Code and select than File > Open folder ... and choose created myMSALApplication1 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 packages and after that create and update .env file. env file holds the secrets.

  • Add packages - add Microsoft.Identity.Client and dotenv.net packages into the project using dotnet add package commands as following.

  
    dotnet add package Microsoft.Identity.Client 
dotnet add package dotenv.net
  
  • Create .env file - create .env file using following commands to hold secrets and open it into code editor to update it’s content.

  
    touch .env
code .env
  
  • Update .env file - Into the .env file add the below code. Replace actual values with CLIENT_ID and TENANT_ID. Actual values are recorded earlier in previous above section. To save file press ctrl + s and then to exit editor press ctrl + q.

  
    CLIENT_ID="YOUR_CLIENT_ID"
TENANT_ID="YOUR_TENANT_ID"
  

Starter Code

Add the following starter code into the application. Let’s replace template code in Program.cs file by using editor in Cloud Shell.

  • Application editing - open Program.cs file to edit it in the Cloud Shell using below command.

  
    code Program.cs
  
  • Replace code - replace existing code of Program.cs with the following code.

  
    using Microsoft.Identity.Client;
using dotenv.net;

// From .env file - load environment variables 
DotEnv.Load();
var envVars = DotEnv.Read();

string clientID = envVars["CLIENT_ID"];
string tenantID = envVars["TENANT_ID"];

// DEFINE SCOPES AND CREATE CLIENT 

// ACQUIRE ACCESS TOKEN
  
  • Save & close - Press ctrl + s to save changes and continue.

Complete Code

Add following code to complete the remaining application. Now let’s update the code fore commented lines for specific operations one by one with description.

  • Define scopes and create client - Locate // DEFINE SCOPES AND CREATE CLIENT comment, then add following code directly beneath comment. Here, PublicClientApplicationBuilder.Create static method is used to build instance of PublicClientApplication from MSAL.

  
    // Define scopes required for authentication
string[] scopes = { "User.Read" };

// Build MSAL public client application with authority and redirect URI
var app = PublicClientApplicationBuilder.Create(clientID)
    .WithAuthority(AzureCloudInstance.AzurePublic, tenantID)
    .WithDefaultRedirectUri()
    .Build();
  
  • Acquire token access - Locate // ACQUIRE ACCESS TOKEN comment, then add following code directly beneath comment.

  
    // Acquire token access silently
AuthenticationResult result;

try
{
    // Try to acquire token silently from cache for the first available account
    var accounts = await app.GetAccountsAsync();
    result = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault()).ExecuteAsync();
}
catch (MsalUiRequiredException)
{
    // Specific exception's handeling
    // Silent token acquisition fails, prompt to user silently
    result = await app.AcquireTokenInteractive(scopes).ExecuteAsync();
}
// Output acquired the access token
Console.WriteLine($"Accessed Token:\n{result.AccessToken}. Press any key to continue!");
Console.ReadLine();
  

Now it’s time to save and close the file by pressing Ctrl + s to save file and then Ctrl + q to exit the editor. Here, by with this article a complete code is attached in Program.cs file.

Run application

Now application is complete and next’s task is to run it.

  • Run application using dotnet run command as following:

  
    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.

  
    Access Token:
dseJ7eYCiQiJKA1PiLCJub14jWSI6IlZF.........
  
  • Next time when application is executed there will no required to Accept “Permissions requested” because the granted earlier permission was cached.

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

Here, a complete process flow is described to implement interactive authentication with MSAL.NET SDK. First, registered an application with the Microsoft identity platform. And then, created a .NET console application which implements PublicClientApplicationBuilder class to configure authentication. And last, acquired a token interactively by using user.read Microsoft Graph permission.