Introduction
Microsoft Authentication Library (MSAL) is a Microsoft-developed library that enables applications to authenticate users and obtain access tokens using Microsoft Entra ID, formerly known as Azure Active Directory. It supports applications developed in multiple programming languages and frameworks, including C#, Java, JavaScript, Python, and other supported platforms.
MSAL simplifies authentication by handling token acquisition, token caching, account management, and supported authentication flows. It allows developers to integrate secure authentication into web applications, desktop applications, mobile applications, and background services.
How MSAL Works
MSAL works with Microsoft Entra ID to establish user or application identity and obtain tokens for accessing protected resources.
The general authentication process follows these steps:
- Application Registration: The application is registered in Microsoft Entra ID to obtain a Client ID and configure the required authentication settings.
- Authentication Request: The application uses the appropriate MSAL library to initiate authentication or request a token.
- Identity Verification: Microsoft Entra ID authenticates the user or validates the application's credentials, depending on the authentication flow.
- Token Acquisition: MSAL obtains an access token for the requested resource and permissions.
- API Access: The application sends the access token to a protected API, typically through the HTTP Authorization header.
- Token Validation: The API validates the token and checks authorization requirements before allowing access to protected resources.
- Token Reuse: MSAL can use its token cache to avoid unnecessary authentication requests and attempt silent token acquisition when possible.
MSAL Across Different Programming Languages
MSAL follows common authentication principles across supported programming languages, although the implementation and available features depend on the platform.
- C# and .NET: MSAL.NET is used in .NET applications, including desktop clients, and can be integrated into web applications. ASP.NET Core applications commonly use Microsoft.Identity. Web for authentication integration.
- Java: MSAL4J supports Java applications, including confidential-client applications and services that need to acquire tokens.
- JavaScript: MSAL.js supports browser-based applications and can be used with supported JavaScript frameworks, including React and Angular.
- Python: MSAL Python supports applications that need to acquire tokens for Microsoft identity-protected resources.
- Android: MSAL for Android supports authentication scenarios in Android applications.
- iOS and macOS: MSAL for iOS and macOS supports authentication in applications built for Apple's platforms.
The core concepts remain consistent, but library APIs, supported flows, configuration, and token-cache behavior differ across implementations.
Types of Authentication Flows
MSAL supports different authentication flows depending on the application type and security requirements.
- Interactive Authentication: Used when a user signs in through a browser or supported user interface.
- Silent Token Acquisition: Attempts to obtain a token from the cache or available authentication mechanisms without requiring an interactive sign-in.
- Authorization Code Flow with PKCE: Commonly used by web and public-client applications that authenticate users securely.
- Client Credentials Flow: Used by confidential clients, such as backend services and scheduled jobs, to obtain tokens as an application rather than as a signed-in user.
- On-Behalf-Of Flow: Allows a middle-tier API to obtain a token to call another API on behalf of an authenticated user, subject to the required configuration and permissions.
The appropriate flow should be selected based on the application's architecture. Public clients must not store client secrets, and confidential-client credentials must be protected using suitable secure storage.
Important Components of MSAL
The following components are central to an MSAL implementation:
- Client ID: Uniquely identifies the registered application.
- Tenant ID: Identifies the Microsoft Entra ID directory, where applicable.
- Authority: Specifies the identity provider endpoint used for authentication.
- Scopes: Specify the permissions requested for an API or resource.
- Access Token: Provides the credential used to access a protected resource.
- Token Cache: Stores available authentication tokens and related information to support efficient token acquisition.
- Redirect URI: Specifies the configured return location for supported interactive authentication flows.
An ID token and an access token serve different purposes. An ID token provides information about the authenticated user to the client, whereas an access token is intended for a particular resource or API.
Security Best Practices
When implementing MSAL in enterprise applications, developers should follow established security practices:
- Register applications correctly and configure only the necessary redirect URIs.
- Request the minimum permissions required by the application.
- Use authorization code flow with PKCE where appropriate for public clients.
- Never embed client secrets in browser-based, mobile, or other public-client applications.
- Store confidential-client credentials securely, using services such as Azure Key Vault or supported managed identity configurations where appropriate.
- Validate access tokens at the API boundary and enforce authorization policies.
- Protect token caches and avoid logging access tokens, refresh tokens, or client secrets.
- Monitor authentication failures and review application permissions regularly.
Microsoft Authentication Library (MSAL) provides platform-specific libraries for implementing authentication in Node.js and .NET applications. Both can integrate with Microsoft Entra ID to acquire access tokens and access protected APIs.
1. Node.js — MSAL NodeLibrary: @azure/msal-node
Install the package:
npm install @azure/msal-node
The following example uses the client credentials flow for a backend service.
const {
ConfidentialClientApplication
} = require("@azure/msal-node");
const config = {
auth: {
clientId: process.env.CLIENT_ID,
authority:
`https://login.microsoftonline.com/${process.env.TENANT_ID}`,
clientSecret: process.env.CLIENT_SECRET
}
};
async function getAccessToken() {
const app = new ConfidentialClientApplication(config);
const result = await app.acquireTokenByClientCredential({
scopes: [
"https://graph.microsoft.com/.default"
]
});
if (!result?.accessToken) {
throw new Error("Unable to acquire access token.");
}
console.log("Access token acquired successfully.");
return result.accessToken;
}
getAccessToken().catch(console.error);
How it works:
- The application loads its Client ID, Tenant ID, and client secret from environment variables.
- MSAL Node authenticates the application with Microsoft Entra ID.
- Entra ID issues an access token for the requested resource and permissions.
- The application can use the token to call Microsoft Graph or another appropriately configured API.
- Use cases: Node.js backend services, scheduled jobs, integrations, and server-side applications requiring application-only authentication.
2. .NET — MSAL.NETLibrary: Microsoft.Identity.Client
Install the NuGet package:
dotnet add package Microsoft.Identity.Client
The following example uses the client credentials flow for a .NET backend service.
using Microsoft.Identity.Client;
var clientId = Environment.GetEnvironmentVariable("CLIENT_ID")
?? throw new InvalidOperationException("CLIENT_ID is missing.");
var tenantId = Environment.GetEnvironmentVariable("TENANT_ID")
?? throw new InvalidOperationException("TENANT_ID is missing.");
var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET")
?? throw new InvalidOperationException("CLIENT_SECRET is missing.");
var app = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithAuthority(
$"https://login.microsoftonline.com/{tenantId}")
.WithClientSecret(clientSecret)
.Build();
var result = await app.AcquireTokenForClient(
new[] { "https://graph.microsoft.com/.default" })
.ExecuteAsync();
Console.WriteLine("Access token acquired successfully.");
Console.WriteLine($"Expires: {result.ExpiresOn}");
How it works:- The .NET application creates a confidential-client instance.
- MSAL.NET uses the configured application credentials to request a token.
- Microsoft Entra ID validates the application and issues a token if the required permissions and consent are configured.
- The application uses the token to call the protected API.
Use cases: ASP.NET Core backend services, Azure-hosted applications, scheduled jobs, and enterprise integrations.
3. Calling an API with the Access TokenBoth Node.js and .NET applications can call a protected API using the acquired access token.
Example HTTP request:
GET https://graph.microsoft.com/v1.0/usersAuthorization: Bearer ACCESS_TOKEN
This example requires appropriate Microsoft Graph application permissions and admin consent. For application-only access, use an endpoint supported by the granted application permissions; /me is intended for delegated user access.
Security Best Practices
- Store secrets in a secure service such as Azure Key Vault; never commit them to source control.
- Use managed identities for supported Azure workloads where appropriate.
- Grant only the permissions the application needs.
- Use .default for the configured permissions of the requested resource in the client credentials flow.
- Allow MSAL to manage token acquisition and caching rather than manually creating tokens.
- Validate access tokens and enforce authorization at the receiving API.
Conclusion
MSAL Node and MSAL.NET provide equivalent core capabilities for authenticating backend applications and acquiring access tokens. The main difference is the language-specific library and API. Both integrate with Microsoft Entra ID and support secure access to Microsoft Graph and other protected APIs when the appropriate permissions and application configuration are in place.
Benefits of Using MSAL
MSAL provides a consistent approach to Microsoft identity authentication across supported platforms. It reduces the need to implement authentication protocols manually, supports token acquisition and caching, integrates with Microsoft Entra ID, and enables applications to access protected Microsoft services and custom APIs.
For organizations working with multiple technologies, MSAL helps standardize authentication patterns while allowing each application to use the library appropriate to its programming language and platform.
Library: @azure/msal-node
Install the package:
npm install @azure/msal-node
The following example uses the client credentials flow for a backend service.
const {
ConfidentialClientApplication
} = require("@azure/msal-node");
const config = {
auth: {
clientId: process.env.CLIENT_ID,
authority:
`https://login.microsoftonline.com/${process.env.TENANT_ID}`,
clientSecret: process.env.CLIENT_SECRET
}
};
async function getAccessToken() {
const app = new ConfidentialClientApplication(config);
const result = await app.acquireTokenByClientCredential({
scopes: [
"https://graph.microsoft.com/.default"
]
});
if (!result?.accessToken) {
throw new Error("Unable to acquire access token.");
}
console.log("Access token acquired successfully.");
return result.accessToken;
}
getAccessToken().catch(console.error);
- The application loads its Client ID, Tenant ID, and client secret from environment variables.
- MSAL Node authenticates the application with Microsoft Entra ID.
- Entra ID issues an access token for the requested resource and permissions.
- The application can use the token to call Microsoft Graph or another appropriately configured API.
- Use cases: Node.js backend services, scheduled jobs, integrations, and server-side applications requiring application-only authentication.
Library: Microsoft.Identity.Client
Install the NuGet package:
dotnet add package Microsoft.Identity.Client
The following example uses the client credentials flow for a .NET backend service.
using Microsoft.Identity.Client;
var clientId = Environment.GetEnvironmentVariable("CLIENT_ID")
?? throw new InvalidOperationException("CLIENT_ID is missing.");
var tenantId = Environment.GetEnvironmentVariable("TENANT_ID")
?? throw new InvalidOperationException("TENANT_ID is missing.");
var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET")
?? throw new InvalidOperationException("CLIENT_SECRET is missing.");
var app = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithAuthority(
$"https://login.microsoftonline.com/{tenantId}")
.WithClientSecret(clientSecret)
.Build();
var result = await app.AcquireTokenForClient(
new[] { "https://graph.microsoft.com/.default" })
.ExecuteAsync();
Console.WriteLine("Access token acquired successfully.");
Console.WriteLine($"Expires: {result.ExpiresOn}");
- The .NET application creates a confidential-client instance.
- MSAL.NET uses the configured application credentials to request a token.
- Microsoft Entra ID validates the application and issues a token if the required permissions and consent are configured.
- The application uses the token to call the protected API.
- Store secrets in a secure service such as Azure Key Vault; never commit them to source control.
- Use managed identities for supported Azure workloads where appropriate.
- Grant only the permissions the application needs.
- Use .default for the configured permissions of the requested resource in the client credentials flow.
- Allow MSAL to manage token acquisition and caching rather than manually creating tokens.
- Validate access tokens and enforce authorization at the receiving API.








.gif)
0 Comments