| services | active-directory | ||||
|---|---|---|---|---|---|
| platforms | dotnet | ||||
| author | TiagoBrenck | ||||
| level | 200 | ||||
| client | .NET Desktop (Console) | ||||
| service | Microsoft Graph | ||||
| endpoint | Microsoft identity platform | ||||
| page_type | sample | ||||
| languages |
|
||||
| products |
|
||||
| description | This sample demonstrates a .NET Desktop (Console) application calling Microsoft Graph using custom web UI HTML |
This sample demonstrates how to use a custom web UI HTML on MSAL.NET.
- The .NET Desktop (Console) application uses the Microsoft Authentication Library (MSAL) to obtain a JWT access token from Microsoft Entra ID.
- Once the authorization request is finished (successfully or not), the customized HTML will be shown and the browser will return the response to MSAL.
The console application:
- gets an access token from Microsoft Entra ID interactively using a custom web UI HTML
- and then calls the Microsoft Graph
/meendpoint to get the user information, which it then displays in the console.
To run this sample, you'll need:
- Visual Studio 2019
- An Internet connection
- a Microsoft Entra tenant. For more information on how to get a Microsoft Entra tenant, see How to get a Microsoft Entra tenant
- A user account in your Microsoft Entra tenant. This sample will not work with a Microsoft account (formerly Windows Live account). Therefore, if you signed in to the Microsoft Entra admin center with a Microsoft account and have never created a user account in your directory before, you need to do that now.
From your shell or command line:
git clone https://github.com/Azure-Samples/ms-identity-dotnet-desktop-tutorial.gitor download and extract the repository .zip file.
Given that the name of the sample is quiet long, and so are the names of the referenced NuGet packages, you might want to clone it in a folder close to the root of your hard drive, to avoid file size limitations on Windows.
There is one project in this sample. To register it, you can:
- either follow the steps Step 2: Register the sample with your Microsoft Entra tenant and Step 3: Configure the sample to use your Microsoft Entra tenant
- or use PowerShell scripts that:
- automatically creates the Microsoft Entra applications and related objects (passwords, permissions, dependencies) for you. Note that this works for Visual Studio only.
- modify the Visual Studio projects' configuration files.
Expand this section if you want to use this automation:
-
On Windows, run PowerShell and navigate to the root of the cloned directory
-
In PowerShell run:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force
-
Run the script to create your Microsoft Entra application and configure the code of the sample application accordingly.
-
In PowerShell run:
cd .\AppCreationScripts\ .\Configure.ps1
Other ways of running the scripts are described in App Creation Scripts The scripts also provide a guide to automated application registration, configuration and removal which can help in your CI/CD scenarios.
-
Open the Visual Studio solution and click start to run the code.
Follow the steps below to manually walk through the steps to register and configure the applications.
As a first step you'll need to:
- Sign in to the Microsoft Entra admin center using either a work or school account or a personal Microsoft account.
- If your account is present in more than one Microsoft Entra tenant, select your profile at the top right corner in the menu on top of the page, and then switch directory. Change your portal session to the desired Microsoft Entra tenant.
-
Navigate to the Microsoft identity platform for developers App registrations page.
-
Click New registration on top.
-
In the Register an application page that appears, enter your application's registration information:
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
Console-Interactive-MultiTarget-v2. - Change Supported account types to Accounts in any organizational directory and personal Microsoft accounts (e.g. Skype, Xbox, Outlook.com).
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
-
Click on the Register button in bottom to create the application.
-
In the app's registration screen, find the Application (client) ID value and record it for use later. You'll need it to configure the configuration file(s) later in your code.
-
In the app's registration screen, click on the Authentication blade in the left.
- If you don't have a platform added yet, click on Add a platform and select the Public client (mobile & desktop) option.
- In the Redirect URIs section, enter the following redirect URIs.
http://localhost
- In the Redirect URIs | Suggested Redirect URIs for public clients (mobile, desktop) section, select https://login.microsoftonline.com/common/oauth2/nativeclient
-
Click the Save button on top to save the changes.
-
In the app's registration screen, click on the API permissions blade in the left to open the page where we add access to the Apis that your application needs.
- Click the Add a permission button and then,
- Ensure that the Microsoft APIs tab is selected.
- In the Commonly used Microsoft APIs section, click on Microsoft Graph
- In the Delegated permissions section, select the User.Read in the list. Use the search box if necessary.
- Click on the Add permissions button at the bottom.
Open the project in your IDE (like Visual Studio) to configure the code.
In the steps below, "ClientID" is the same as "Application ID" or "AppId".
- Open the
Console-Interactive-MultiTarget\appsettings.jsonfile - Find the app key
ClientIdand replace the existing value with the application ID (clientId) of theConsole-Interactive-MultiTarget-v2application copied from the Microsoft Entra admin center. - Find the app key
TenantIdand replace the existing value with your Microsoft Entra tenant ID.
Clean the solution, rebuild the solution, and run it.
Start the application, sign-in and check the result in the console.
MSAL has the class SystemWebViewOptions.cs which allows you to set properties to customize the UI after the authentication request.
In this sample, we customized the HTML for successful and failure authorization requests, but more options are available. Please refer to the SystemWebViewOptions.cs documentation for more options.
1- Customizing the success or failure HTML message:
private static SystemWebViewOptions GetCustomHTML()
{
return new SystemWebViewOptions
{
HtmlMessageSuccess = @"<html style='font-family: sans-serif;'>
<head><title>Authentication Complete</title></head>
<body style='text-align: center;'>
<header>
<h1>Custom Web UI</h1>
</header>
<main style='border: 1px solid lightgrey; margin: auto; width: 600px; padding-bottom: 15px;'>
<h2 style='color: limegreen;'>Authentication complete</h2>
<div>You can return to the application. Feel free to close this browser tab.</div>
</main>
</body>
</html>",
HtmlMessageError = @"<html style='font-family: sans-serif;'>
<head><title>Authentication Failed</title></head>
<body style='text-align: center;'>
<header>
<h1>Custom Web UI</h1>
</header>
<main style='border: 1px solid lightgrey; margin: auto; width: 600px; padding-bottom: 15px;'>
<h2 style='color: salmon;'>Authentication failed</h2>
<div><b>Error details:</b> error {0} error_description: {1}</div>
<br>
<div>You can return to the application. Feel free to close this browser tab.</div>
</main>
</body>
</html>"
};
}2- Using .WithSystemWebViewOptions() on the AcquireTokenInteractive request, passing the customized SystemWebViewOptions object so MSAL can use it to display the response.
var app = PublicClientApplicationBuilder.Create(appConfiguration.ClientId)
.WithAuthority(_authority)
.WithRedirectUri(appConfiguration.RedirectUri)
.Build();
string[] scopes = new[] { "user.read" };
AuthenticationResult result;
try
{
var accounts = await app.GetAccountsAsync();
result = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault())
.ExecuteAsync();
}
catch (MsalUiRequiredException)
{
result = await app.AcquireTokenInteractive(scopes)
.WithSystemWebViewOptions(_customWebView) // Using the custom html
.ExecuteAsync();
}3- Once the authorization response gets back, the opened tab will display the custom successful or failure message.
Use Stack Overflow to get support from the community.
Ask your questions on Stack Overflow first and browse existing issues to see if someone has asked your question before.
Make sure that your questions or comments are tagged with [azure-active-directory msal dotnet].
If you find a bug in the sample, please raise the issue on GitHub Issues.
To provide a recommendation, visit the following User Voice page.
If you'd like to contribute to this sample, see CONTRIBUTING.MD.
This project has adopted the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.
For more information, see MSAL.NET's conceptual documentation:
-
Microsoft identity platform (Microsoft Entra ID for developers)
-
Quickstart: Register an application with the Microsoft identity platform
-
Quickstart: Configure a client application to access web APIs
-
Understanding Microsoft Entra application consent experiences
-
Application and service principal objects in Microsoft Entra ID
For more information about how OAuth 2.0 protocols work in this scenario and other scenarios, see Authentication Scenarios for Microsoft Entra ID.


