This guide explains how to initialize public and confidential client applications using MSAL.NET for authenticating users and acquiring tokens from Microsoft Entra ID.
In this guide, you’ll learn how to initialize both public and confidential client applications using MSAL.NET—a robust library provided by Microsoft for authenticating users and acquiring tokens from Microsoft Entra ID.The code snippet below demonstrates how to initialize a public client application as well as a confidential client application:
Public client applications, commonly used in desktop or mobile contexts, do not store secrets. In contrast, confidential client applications (such as web APIs or backend servers) require a client secret and a redirect URI for secure authentication callbacks.
Using MSAL.NET, you can securely manage both application types, enabling seamless access to Azure Active Directory resources. This initialization process lays the foundation for more advanced authentication configurations that are covered in the following sections.
Building a Confidential Client Application in Visual Studio Code
In this section, we will build a confidential client application using Visual Studio Code. The process involves using the ConfidentialClientApplicationBuilder and providing essential details such as the client ID, client secret, required scopes, and authority URI built with your tenant ID. Below is a typical setup:
This example shows how the application initializes and requests an access token for specified scopes. On success, the access token is printed to the console; if an error occurs, the exception message is displayed.
Ensure you securely copy and store these credentials. The password will not be displayed again, so avoid hard coding these values in your source code. Utilize a configuration file with proper security measures for production environments.
For testing purposes, you may temporarily include them in your code, but always follow security best practices when preparing your production applications.
Once you update the tenant ID, client ID, and client secret in your code, execute the application. An access token will be generated and printed to the console. To verify the token:
This tool displays token details, such as the app ID and display name, which should match those from the service principal created with the Azure CLI.The JSON output of the token might include fragments similar to:
This article demonstrated how to work with MSAL.NET to initialize both public and confidential client applications, build a confidential client application in Visual Studio Code, and create a service principal using the Azure CLI. By following these steps, you can securely authenticate and efficiently access Azure Active Directory resources.Up next, we will discuss Shared Access Signatures and their critical role in enhancing modern application security.