AWS/Azure/OpenShift

How to implement Interactive Authentication using MSAL dotNET

oauth2final

MSAL is the acronym for Microsoft Authentication Library, according to Microsoft, (MSAL) can be used to provide secure access to Microsoft Graph, other Microsoft APIs, third-party web APIs, or your own web API. MSAL supports many different application architectures and platforms including .NET, JavaScript, Java, Python, Android, and iOS. Microsoft provides a powerful identity ecosystem, but applications must be registered to support authentication and authorization. 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. You establish a trust relationship between the defined application and the Microsoft identity platform when you develop an application. It’s worth noting that the trust is only one-way, in that the program trusts Microsoft but not the other way around.

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.

MSAL provides a uniform API for a variety of platforms, allowing you to obtain tokens in a variety of 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

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

Step1: Create an app registration in Azure Active directory Managed Identity

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

MANAGE
app registration

The next to click new app registration and fill in the all the required information as shown below

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 and as such, we selected 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

client-id
App ID

After the app is registered, the platform automatically generated the Client ID and Object ID, as shown above. The tenant ID is unique to the tenant. We shall be using both application and tenant ID in the next step when we create a dotnet app in visual studio code.

Step 2: 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
mkdir
vscode mkdir

Create the .NET console app.

dotnet new console
dotnet-new
console app created

Open the techdirectarchive-app folder in vscode

code . -r
vscode
files opened in Vs code
Step3: Add the necessary 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

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

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

Change the Main method to enable async.

public static async Task Main(string[] args)

Add code for the interactive authentication. 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. In the code we’re specifying the Public cloud, and using the tenant for the app we registered.

Step 4: Acquire a token

When you registered  techdirectarchive-app it automatically generated an API permission user.read for Microsoft Graph. 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" };

Add code to request the token and write the result out 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 there are multiple accounts listed select the one associated with the tenant used in the app. If this is the first time you’ve authenticated to the registered app you will receive a Permissions 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

Microsoft Authentication Library helps with the necessary authentication and permissions that applications need so as to access services. The steps are shown in the article above.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x