Exercise - Implement interactive authentication by using MSAL.NET
In this exercise you learn how to perform the following actions:
- Register an application with the Microsoft identity platform
- Use the
PublicClientApplicationBuilder
class in MSAL.NET - Acquire a token interactively in a console application
Prerequisites
- An Azure account with an active subscription. If you don't already have one, you can sign up for a free trial at https://azure.com/free
- Visual Studio Code: You can install Visual Studio Code from https://code.visualstudio.com.
- A version of the .NET SDK https://dotnet.microsoft.com/download/dotnet (6.0, 7.0, or 8.0)
Register a new application
Sign in to the portal: https://portal.azure.com
Search for and select Microsoft Entra ID.
Under Manage, select App registrations > New registration.
When the Register an application page appears, enter your application's registration information:
Field Value Name az204appreg
Supported account types Select Accounts in this organizational directory only Redirect URI (optional) Select Public client/native (mobile & desktop) and enter http://localhost
in the box to the right.Select Register.
Microsoft Entra ID assigns a unique application (client) ID to your app, and you're taken to your application's Overview page.
Set up the console application
Launch Visual Studio Code and open a terminal by selecting Terminal and then New Terminal.
Create a folder for the project and change in to the folder.
md az204-auth cd az204-auth
Create the .NET console app.
dotnet new console
Open the az204-auth folder in Visual Studio Code.
code . -r
Build the console app
In this section, you add the necessary packages and code to the project.
Add packages and using statements
Add the
Microsoft.Identity.Client
package to the project in a terminal in Visual Studio Code.dotnet add package Microsoft.Identity.Client
Open the Program.cs file and add
using
statements to includeMicrosoft.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
You need two variables to hold the Application (client) and Directory (tenant) IDs. You can copy those values from the portal. Add the following code and replace the string values with the appropriate values from the 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();
Code Description .Create
Creates 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.
Acquire a token
When you registered the az204appreg app, it automatically generated an API permission user.read
for Microsoft Graph. You use that permission to acquire a token.
Set the permission scope for the token request. Add the following code below 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 completed application
The contents of the Program.cs file should resemble the following example:
using System;
using System.Threading.Tasks;
using Microsoft.Identity.Client;
namespace az204_auth
{
class Program
{
private const string _clientId = "APPLICATION_CLIENT_ID";
private const string _tenantId = "DIRECTORY_TENANT_ID";
public static async Task Main(string[] args)
{
var app = PublicClientApplicationBuilder
.Create(_clientId)
.WithAuthority(AzureCloudInstance.AzurePublic, _tenantId)
.WithRedirectUri("http://localhost")
.Build();
string[] scopes = { "user.read" };
AuthenticationResult result = await app.AcquireTokenInteractive(scopes).ExecuteAsync();
Console.WriteLine($"Token:\t{result.AccessToken}");
}
}
}
Run the application
In the Visual Studio Code terminal run
dotnet build
to check for errors, thendotnet run
to run the app.The app opens 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 receive a Permissions requested notification asking you to approve the app to read data associated with your account. Select Accept.
You should see the results similar to the example below in the console.
Token: eyJ0eXAiOiJKV1QiLCJub25jZSI6IlVhU.....