Skip to content

TechDirectArchive

Hands-on IT, Cloud, Security, Veeam & DevOps

  • Home
  • About
  • Advertise With US
  • Contact
  • Reviews
  • Toggle search form

How to implement Interactive Authentication using MSAL dotNET

Posted on 06/06/202219/07/2023 Raphael Gab-Momoh By Raphael Gab-Momoh 5 Comments on How to implement Interactive Authentication using MSAL dotNET
  1. Home
  2. AWS/Azure/OpenShift
  3. How to implement Interactive Authentication using MSAL dotNET
oauth2final

MSAL is the acronym for Microsoft Authentication Library; according to Microsoft, (MSAL) can provide secure access to Microsoft Graph, other Microsoft APIs, third-party web APIs, or your web API. Furthermore, MSAL supports many application architectures and platforms, including .NET, JavaScript, Java, Python, Android, and iOS. Microsoft provides a robust identity ecosystem, but applications must be registered to support authentication and authorization. This article explores how to implement interactive authentication using MSAL dotNET.

Other guides can be found in How to Install and configure JIRA on Linux and How to Install and configure Elasticsearch on Linux. 

To that end, the App registrations pane in Azure AD allows you to establish application registrations and grant permissions to them. When developing an application, you establish a trust relationship between the defined application and the Microsoft identity platform. It’s worth noting that the trust is only one way in that the program trusts Microsoft but not vice versa.

The following Azure Apps features are within your control. Only registered applications are managed by the Microsoft identity platform for identity and access management (IAM). Whether your application is a client app, such as a web or mobile app, or a web API that supports a client app, registering creates a trust connection between your app and the identity provider, the Microsoft identity platform.

Managed identities provide an identity for applications to use when connecting to resources that support Azure Active Directory (Azure AD) authentication. Applications may use the managed identity to obtain Azure AD tokens.

Why Implement Interactive Authentication Using MSAL dotNET

MSAL provides a uniform API for various platforms, allowing you to obtain tokens in various methods. The following are some of the advantages of using MSAL:

  1. There’s no need to use OAuth libraries or code against the protocol directly in your project.
  2. Tokens are acquired on behalf of a user or an application (when applicable to the platform).
  3. Maintains a token cache and automatically refreshes tokens when they’re about to expire. You are not responsible for managing token expiration on your own.
  4. Assists you in configuring your program via configuration files.
  5. By exposing actionable errors, logging, and telemetry, it assists you in troubleshooting your program

At the end of this article, we will understand how the managed identity platform of Microsoft works & do the following:

  1. Register an application with the Microsoft Identity platform
  2. Use the PublicClientApplicationBuilder class in MSAL.NET
  3. Acquire a token interactively in a console application

Requirements for Implementing Interactive Authentication

Below are the requirements to implement Interactive Authentication.

  1. An Azure account with a subscription
  2. Visual studio code
  3. Basic knowledge of how to create a directory

Demo: let’s build an app that uses MSAL for authentication

Below are steps for implementing interactive authentication using MSAL.

Step 1: Create an app registration in the Azure Active directory Managed Identity

To register your app, sign in to the Azure portal and search for the active directory. Under Manage, select App registrations > New registration

How to implement Interactive Authentication using MSAL dotNET-MANAGE
app registration

Next, click new app registration and fill in all the required information as shown below

How to implement Interactive Authentication using MSAL dotNET-newappreg
new app registration

We decided to call the app we are registering.”techdirectarchive app. In the example exercise, we assumed that the account is a single account as it is not an organizational account. As such, we selected a single tenant as the organizational type. For redirect uri , we selected web and wrote http://localhost and then we hit on the blue register button

How to implement Interactive Authentication using MSAL dotNET-client-id
App ID

After registering the app, the platform automatically generates the Client ID and Object ID, as shown above. The tenant ID is unique to this. We shall use both application and tenant ID in the next step when creating a dotnet app in visual studio code.

Step 2: Create a DotNet Application

Therefore, to implement interactive authentication, you need to create a DotNet application. The steps are as shown below:

  • Launch Visual Studio Code and open a terminal by selecting Terminal and then New Terminal.
  • create a project directory or folder & change into that directory
mkdr techdirectarchive-app
cd techdirectarchive-app
How to implement Interactive Authentication using MSAL dotNET-mkdir
vscode mkdir

Then, create the .NET console app.

dotnet new console
dotnet-new
console app created

Afterward, open the techdirectarchive-app folder in vscode

code . -r
vscode
files opened in Vs code
Step 3: Add the necessary packages to the console app

After creating the dotNET application, the next step in implementing interactive authentication is the addition of packages to the console app.

Add the Microsoft.Identity.Client package to the project in a terminal in VS Code

dotnet add package Microsoft.Identity.Client

Therefore, open the Program.cs file and add using statements to include Microsoft.Identity.Client and enable async operations.

using System.Threading.Tasks;
using Microsoft.Identity.Client;

Then, change the Main method to enable async.

public static async Task Main(string[] args)

Following that, add code for the interactive authentication. Subsequently, the Application (client) and Directory (tenant) IDs will be stored in two variables. Those values can be copied from the Azure portal.

private const string _clientId = "APPLICATION_CLIENT_ID";
private const string _tenantId = "DIRECTORY_TENANT_ID";

Use the PublicClientApplicationBuilder class to build out the authorization context.

var app = PublicClientApplicationBuilder
    .Create(_clientId)
    .WithAuthority(AzureCloudInstance.AzurePublic, _tenantId)
    .WithRedirectUri("http://localhost")
    .Build();

.Create generates a PublicClientApplicationBuilder from a clientID.
.WithAuthority Adds a known Authority corresponding to an ADFS server. However, in the code, we specify the Public cloud and use the tenant for the app we registered.

Step 4: Acquire a token

Acquiring a token is another step to take when implementing interactive authentication.

When you registered  techdirectarchive-app , it automatically generated API permission user.read for Microsoft Graph. Hence, we’ll use that permission to acquire a token.

  • Set the permission scope for the token request. Add the following code to the PublicClientApplicationBuilder.
string[] scopes = { "user.read" };

Then, add code to request the token and write the result to the console.

AuthenticationResult result = await app.AcquireTokenInteractive(scopes).ExecuteAsync();

Console.WriteLine($"Token:\t{result.AccessToken}");

Review the code as shown below :

code1
code
Step 5: Run the Application

We can check for errors with the command

dotnet build 
build1
build

We can run the application with the command:

dotnet run

The app will open the default browser prompting you to select the account you want to authenticate with. If multiple accounts are listed, select the one associated with the tenant used in the app. Suppose this is the first time you’ve authenticated to the registered app. In that case, you will receive a Permission requested notification asking you to approve the app to read data associated with your account. Select Accept.

techdirectarchive-app

You should get a token in your console just like the one below

Token: eyJ0eXAiOiJKV1QiLCJub25jZSI6IlVhU.....

Summary

In conclusion, Microsoft Authentication Library helps with the necessary authentication and permissions applications need to access services. The steps above explain how to implement interactive authentication using MSAL dotNET.

Rate this post

Thank you for reading this post. Kindly share it with others.

  • Share on X (Opens in new window) X
  • Share on Reddit (Opens in new window) Reddit
  • Share on LinkedIn (Opens in new window) LinkedIn
  • Share on Facebook (Opens in new window) Facebook
  • Share on Pinterest (Opens in new window) Pinterest
  • Share on Tumblr (Opens in new window) Tumblr
  • Share on Telegram (Opens in new window) Telegram
  • Share on WhatsApp (Opens in new window) WhatsApp
  • Share on Mastodon (Opens in new window) Mastodon
  • Share on Bluesky (Opens in new window) Bluesky
  • Share on Threads (Opens in new window) Threads
  • Share on Nextdoor (Opens in new window) Nextdoor
AWS/Azure/OpenShift Tags:Active Directory

Post navigation

Previous Post: Capture and Record your Screen in Windows 10 with Xbox Game Bar
Next Post: Convert a PEM Key to a PPK Key on a Linux and Windows

Related Posts

  • amazon ec2 multiple ips 1
    What to note before assigning Multiple IPs’ to an Instance AWS/Azure/OpenShift
  • DevOps
    Create an App Service Plan with Continuous Deployment to deploy a .NET Application from GitHub AWS/Azure/OpenShift
  • azure just in time
    How to secure access to your Virtual Machine with Just-in-Time (JIT) VM Access AWS/Azure/OpenShift
  • Screenshot 2024 02 09 at 1.06.54 PM
    Programmatically Deploying App Service Resources in Azure AWS/Azure/OpenShift
  • Azure AD Logo 1
    How to sync on-premises AD with Azure AD via Azure AD Connect AWS/Azure/OpenShift
  • Install Packages to Amazon Virtual Machine Using Terraform
    How to Install Packages to Amazon VM using Terraform AWS/Azure/OpenShift

More Related Articles

amazon ec2 multiple ips 1 What to note before assigning Multiple IPs’ to an Instance AWS/Azure/OpenShift
DevOps Create an App Service Plan with Continuous Deployment to deploy a .NET Application from GitHub AWS/Azure/OpenShift
azure just in time How to secure access to your Virtual Machine with Just-in-Time (JIT) VM Access AWS/Azure/OpenShift
Screenshot 2024 02 09 at 1.06.54 PM Programmatically Deploying App Service Resources in Azure AWS/Azure/OpenShift
Azure AD Logo 1 How to sync on-premises AD with Azure AD via Azure AD Connect AWS/Azure/OpenShift
Install Packages to Amazon Virtual Machine Using Terraform How to Install Packages to Amazon VM using Terraform AWS/Azure/OpenShift

Comments (5) on “How to implement Interactive Authentication using MSAL dotNET”

  1. Avatar photo Nimrod says:
    13/08/2022 at 9:56 PM

    what is the difference between microsoft.identity.client and microsoft.identity.web?

    Log in to Reply
    1. Raph Raphael Gab-Momoh says:
      13/08/2022 at 10:27 PM

      Microsoft.identity.web is just a collection of ASP.NET Core libraries & it makes it easier to add authentication and authorization capabilities to web apps and web APIs that integrate with the Microsoft identity platform.

      Meanwhile, microsoft.identity.client has the Microsoft Authentication Library for.NET binaries in it (MSAL.NET). Developers may easily access tokens from the Microsoft identity platform by signing users in with their work and school accounts, Microsoft personal accounts, and social identities using MSAL.NET Azure AD B2C

      Log in to Reply
      1. Avatar photo Nimrod says:
        15/08/2022 at 4:44 PM

        Thanks.

  2. Avatar photo Reenu V says:
    31/10/2022 at 5:42 AM

    Thanks for sharing. I tried the similar approach, but I am getting a system exception as below:-

    Could not load file or assembly ‘Microsoft.IdentityModel.Abstractions, Version=6.22.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35’ 
    or one of its dependencies. The system cannot find the file specified.”:”Microsoft.IdentityModel.Abstractions, Version=6.22.0.0, Culture=neutral

    I have added the latest version of ‘Microsoft.IdentityModel.Abstractions’from nuget to my GAC and referencing it. But still have the same issue. Any ideas?

    Log in to Reply
    1. Raph Raphael Gab-Momoh says:
      09/11/2022 at 12:52 AM

      Hi Reenu V,

      Thanks for trying out the steps in the article. If you have not been able to resolve the issue, check out a known solution for it below : Add <_FunctionsSkipCleanOutput>true</_FunctionsSkipCleanOutput> to the .csproj file. This is a workaround, not a solution, because this property is internal and undocumented.

      Cheers

      Log in to Reply

Leave a Reply Cancel reply

You must be logged in to post a comment.

Microsoft MVP

VEEAMLEGEND

vexpert-badge-stars-5

Virtual Background

GoogleNews

Categories

veeaam100

Veeam Vanguard

  • Screenshot 2020 06 25 at 23.38.40
    What is Registry Editor and how to access the registry hives Windows
  • Norton360
    Download and install Norton 360 Anti-Virus on your Mac device Mac
  • screenshot 2020 02 08 at 20.02.50
    Windows 10 Administrative Shortcut command key Windows Server
  • wmic4
    How to find User Security Identifier (SID) in Windows [Part 1] Windows
  • finalelastic
    How to Install and Configure Elasticsearch on Linux  Linux
  • Veeam Agent Error Fix
    Fixing AIX Veeam agent job startup delay issue Network | Monitoring
  • Stop Automatic Driver Updates In Windows
    Prevent Automatic Driver Updates in Windows and Xen-Orchestra Virtualization
  • LAPS PAssword Not Showing Up
    LAPS password not showing up in GUI Windows

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 1,801 other subscribers
  • RSS - Posts
  • RSS - Comments
  • About
  • Authors
  • Write for us
  • Advertise with us
  • General Terms and Conditions
  • Privacy policy
  • Feedly
  • Telegram
  • Youtube
  • Facebook
  • Instagram
  • LinkedIn
  • Tumblr
  • Pinterest
  • Twitter
  • mastodon

Tags

AWS Azure Bitlocker Microsoft Windows PowerShell WDS Windows 10 Windows 11 Windows Deployment Services Windows Server 2016

Copyright © 2025 TechDirectArchive

Loading Comments...

You must be logged in to post a comment.