Token Configuration

Earn 25 points (50 with Pro) in two steps

  1. ① Read through the lesson — each section gets a ✓ as you scroll through it.
  2. ② When every section has a ✓, tap Complete lesson.

0 of 11 read · keep scrolling

✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro

Mastering Token Configuration in Microsoft Entra ID

Introduction: The Architecture of Identity Security

In the modern landscape of distributed applications, the concept of a "perimeter" has effectively vanished. We no longer rely on firewalls to protect our data; instead, we rely on identity. When you register an application in Microsoft Entra ID (formerly Azure Active Directory), you are essentially establishing a trusted relationship between your application and the Microsoft identity platform. The most critical component of this relationship is the token.

Tokens are the digital "passports" that allow your application to prove who a user is and what they are authorized to do. Without proper token configuration, your application is either overly permissive, exposing sensitive data to unauthorized parties, or overly restrictive, creating friction for legitimate users. Understanding how to configure these tokens—specifically ID tokens, access tokens, and refresh tokens—is the difference between a secure, scalable application and one that is a liability.

This lesson explores the technical nuances of token configuration. We will move beyond the default settings and look at how to customize token lifetime, handle claims, and ensure that your application’s communication with the identity provider is both efficient and hardened against common security threats.


Not read yet

Understanding the Token Lifecycle

Before diving into configuration, it is essential to understand the three primary types of tokens generated by Microsoft Entra ID:

  1. ID Tokens: These are used by the application to verify the identity of the user. They contain information about the user (claims) and are intended for the client application to consume.
  2. Access Tokens: These tokens are used by the client to request access to protected resources, such as a web API. They represent the permission granted to the client on behalf of the user.
  3. Refresh Tokens: These are long-lived tokens that allow the client to obtain new access tokens without forcing the user to re-authenticate.

The Mechanism of Issuance

When a user logs in, the application sends a request to the Microsoft identity platform. Once the user is authenticated, the platform issues these tokens. The configuration of these tokens dictates how long they are valid, what information they contain, and how they can be used. If you fail to configure these settings, you rely on the platform defaults, which may not align with your specific security or usability requirements.

Callout: The "Zero Trust" Philosophy In a Zero Trust architecture, tokens are treated as transient, short-lived assets. By reducing the lifetime of an access token, you minimize the "blast radius" of a compromised token. If a token is stolen, it only remains useful for a very short window, forcing the attacker to find a way to refresh it—which is significantly harder if you have implemented conditional access policies.


Not read yet

Configuring Token Lifetimes

One of the most common requirements for enterprise applications is customizing how long a token remains valid. By default, Microsoft Entra ID sets an access token lifetime to one hour. While this is a safe default, it may be too long for highly sensitive financial applications or too short for applications used by field workers with intermittent connectivity.

Why Modify Token Lifetime?

  • Security: Shorter lifetimes mean that if a token is intercepted, the window of opportunity for an attacker is smaller.
  • User Experience: If your session management logic is poor, short token lifetimes can lead to users being kicked out of the application unexpectedly.
  • Compliance: Certain industries require specific session timeout policies that may conflict with standard default settings.

Implementing Policy-Based Token Lifetime

To modify these settings, you use the Microsoft Graph API or PowerShell to create a TokenLifetimePolicy. You then assign this policy to your specific service principal (your registered application).

Step-by-step implementation via PowerShell:

  1. Connect to your tenant: Use the Connect-MgGraph command.
  2. Define the policy: Create a JSON object that defines the lifetime.
  3. Create the policy object: Use New-MgPolicyTokenLifetimePolicy.
  4. Assign the policy: Apply it to the specific application object using Add-MgServicePrincipalPolicy.
# Example: Creating a policy for a shorter access token (30 minutes)
$policyDefinition = @{
    Definition = @('{"TokenLifetimePolicy":{"Version":1,"AccessTokenLifetime":"00:30:00"}}')
    DisplayName = "ThirtyMinuteAccessTokenPolicy"
    IsOrganizationDefault = $false
}

# Create the policy
$policy = New-MgPolicyTokenLifetimePolicy -BodyParameter $policyDefinition

# Apply the policy to your specific app service principal
Add-MgServicePrincipalPolicy -ServicePrincipalId <Your-App-Service-Principal-ID> -PolicyId $policy.Id

Warning: Complexity Risks Be extremely careful when applying custom token policies. If you set lifetimes too aggressively, you might cause excessive traffic to the identity provider, leading to throttling or a degraded user experience. Always test changes in a staging environment before deploying to production.


Not read yet

Customizing Token Claims

Claims are key-value pairs inside a token that provide information about the user or the application. For example, a claim might represent a user's email address, their employee ID, or their specific role within the organization.

Sometimes, your application needs information that isn't included in the standard set of claims. Or, conversely, you might want to remove claims to reduce the token size (which can be important if the token is passed in an HTTP header that has size limits).

Types of Claims

  • Standard Claims: Provided by default (e.g., sub for subject, aud for audience).
  • Optional Claims: Specific attributes you can choose to include (e.g., upn, family_name).
  • Custom Claims: Attributes synced from an on-premises directory or added via API extensions.

How to Configure Optional Claims

You can configure optional claims directly in the Azure portal under the "Token configuration" blade for your registered application.

  1. Navigate to Microsoft Entra ID > App registrations.
  2. Select your application.
  3. Click on Token configuration.
  4. Click Add optional claim.
  5. Choose the token type (ID, Access, or SAML) and select the claims you want to add.

Note: Token Size Limits HTTP headers have size limitations. If you add too many custom claims to an access token, the token might grow too large, causing the web server to reject the request with a "400 Bad Request" or "Request Header Too Large" error. Always keep tokens as lean as possible.


Not read yet

Handling Refresh Tokens and Session Management

Refresh tokens are the "silent" heroes of authentication. They allow your application to fetch a new access token without requiring the user to type their password again. However, they are also a high-value target for attackers.

Refresh Token Security

To secure refresh tokens, Microsoft Entra ID allows you to configure Refresh Token Lifetime and Refresh Token Max Inactive Time.

  • Max Inactive Time: If the user hasn't used the application for this amount of time, the refresh token expires. This is an excellent way to force re-authentication for inactive sessions.
  • Max Lifetime: This is the absolute time after which a refresh token is no longer valid, even if the user is active.

Best Practices for Refresh Token Management

  • Use Refresh Token Rotation: This is a security feature that issues a new refresh token every time a new access token is requested. If an attacker steals a refresh token and uses it, the legitimate user will eventually use their own token, which will invalidate the attacker's token and alert the system to potential fraud.
  • Implement Conditional Access: Use Microsoft Entra Conditional Access to require re-authentication based on risk levels, device compliance, or geographic location.

Not read yet

Comparison: Access Tokens vs. ID Tokens

It is common for developers to confuse the two. The following table highlights their differences to ensure you use them correctly in your code.

Feature ID Token Access Token
Purpose Authenticate the user Authorize access to an API
Consumer The client application (the UI) The Resource Server (the API)
Content User profile info (name, email) Scopes, roles, permissions
Lifetime Usually short Configurable (usually 1 hour)
Validation Verified by the client app Verified by the API

Practical Implementation: Validating Tokens in an API

Once you have configured the tokens, your API must be able to validate them. When an incoming request hits your API, it should contain an Authorization: Bearer <token> header.

Steps for Validation

  1. Check the Signature: Verify that the token was signed by Microsoft using the public keys retrieved from the OpenID Connect discovery endpoint.
  2. Verify the Issuer: Ensure the token came from your specific Microsoft Entra tenant.
  3. Verify the Audience: Ensure the token was intended for your API (aud claim).
  4. Check Expiration: Ensure the current time is before the exp claim.

Code Example (C# / .NET):

// In your Startup.cs or Program.cs
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));

// The middleware automatically handles the following:
// 1. Signature validation
// 2. Issuer validation
// 3. Audience validation
// 4. Expiration validation

This code snippet demonstrates the "best practice" approach. Never attempt to write your own token validation logic if a well-supported library exists. Hand-rolled validation is the number one cause of security vulnerabilities in authentication implementations.


Not read yet

Common Pitfalls and How to Avoid Them

Even experienced developers fall into traps when configuring tokens. Here are the most frequent mistakes:

1. Hard-coding Token Lifetimes

Developers often set a very long lifetime to avoid "annoying the users." This is a security failure. If a user leaves their laptop open at a coffee shop and a malicious actor gains access, a long-lived token gives that actor a massive window of opportunity.

  • Solution: Use standard lifetimes and implement robust session management in the UI.

2. Using ID Tokens for Authorization

Some developers use the information inside an ID token to make decisions about whether a user can access a specific API endpoint. This is dangerous because ID tokens are meant for the client, not the resource server.

  • Solution: Always use Access Tokens for API authorization.

3. Ignoring Scope (Least Privilege)

Developers often request User.ReadWrite.All when they only need User.Read. This violates the principle of least privilege. If your app is compromised, the attacker inherits all those permissions.

  • Solution: Request the narrowest possible scopes required for the application to function.

4. Failing to Handle Token Expiration

Applications often crash or show ugly errors when a token expires.

  • Solution: Build logic into your frontend to "silently" refresh the token using a hidden iframe or background request before it expires. Microsoft’s MSAL (Microsoft Authentication Library) handles this automatically if implemented correctly.

Callout: The Role of MSAL The Microsoft Authentication Library (MSAL) is your best friend. It abstracts away the complexity of token acquisition, caching, and refreshing. By using MSAL, you automatically get benefits like token caching, which prevents unnecessary network calls to the identity provider, improving performance and reliability.


Not read yet

Advanced Token Configuration: Claims Mapping

In some enterprise scenarios, you might need to map claims from an on-premises Active Directory to the cloud. Microsoft Entra ID allows for Claims Mapping Policies. This is an advanced feature used when you need to change the default claim names or values to support legacy applications that expect specific claim formats.

When to use Claims Mapping

  • Legacy App Migration: You are moving an app from on-premises to the cloud, and the app expects a claim named EmployeeNumber instead of the standard oid or sub.
  • Compatibility: You are integrating with third-party systems that require specific claim formatting.

Configuring Claims Mapping

Claims mapping involves creating a policy and assigning it to the Service Principal. Because this is a complex operation, it is recommended to only use it when standard optional claims are insufficient.

  1. Define the policy: Create a JSON file defining the mapping.
  2. Upload the policy: Use the New-MgPolicyClaimsMappingPolicy command.
  3. Assign the policy: Use Add-MgServicePrincipalPolicy.

Note: This is a high-level administrative task. Always document these mappings thoroughly, as they represent "hidden" logic that can confuse future developers.


Not read yet

Security Best Practices Checklist

To ensure your token configuration is as secure as possible, follow these guidelines:

  • Use HTTPS Everywhere: Never transmit tokens over plain HTTP. Tokens are sensitive credentials; if they are intercepted, the identity of the user is compromised.
  • Store Tokens Securely: In web applications, store tokens in memory, not in localStorage or sessionStorage, which are vulnerable to Cross-Site Scripting (XSS) attacks. Use secure, HttpOnly cookies for session management.
  • Rotate Secrets: If your application uses a client secret to request tokens, rotate that secret regularly and store it in a secure vault like Azure Key Vault.
  • Audit Regularly: Use the Microsoft Entra sign-in logs to monitor token usage. Look for anomalies, such as tokens being used from unexpected geographic locations or devices.
  • Implement Conditional Access: Always enforce Multi-Factor Authentication (MFA) for sensitive applications, regardless of token lifetime.

Not read yet

Troubleshooting Token Issues

Even with perfect configuration, things can go wrong. Here is how to approach troubleshooting:

The "401 Unauthorized" Error

This is the most common error. It usually means:

  1. The token has expired.
  2. The token was sent to the wrong audience (the aud claim doesn't match your API).
  3. The signature validation failed (the token was tampered with or the wrong keys were used).

Debugging with JWT.ms

Microsoft provides a very useful tool called jwt.ms. You can paste the contents of your token (the Base64 encoded string) into this site, and it will decode the claims for you. This is invaluable for verifying that the tokens being issued contain the claims you expect.

  • Tip: Never paste a production token into an external tool if it contains sensitive PII (Personally Identifiable Information). Use a test tenant for debugging.

Summary and Key Takeaways

Configuring tokens in Microsoft Entra ID is a fundamental skill for any developer working in the Microsoft ecosystem. By moving away from default configurations and tailoring token behavior to your application's specific needs, you achieve a balance between high security and a seamless user experience.

Key takeaways from this lesson:

  1. Tokens are foundational: They are the primary mechanism for identity and authorization. Treat them as sensitive credentials at all times.
  2. Lifetime matters: Balance security and user experience by customizing token lifetimes. Shorter is generally better for security, but ensure your application handles refreshing gracefully.
  3. Use MSAL: Do not attempt to manage tokens manually. Use the Microsoft Authentication Library (MSAL) to handle acquisition, caching, and refresh logic.
  4. Principle of Least Privilege: Request only the scopes your application absolutely needs. This limits the potential damage if your application is ever compromised.
  5. Validate on the Server: Always validate tokens on the resource server (API). Never trust a token that hasn't been verified against the issuer's public keys.
  6. Avoid XSS: Store tokens in memory or secure cookies to prevent them from being stolen by malicious scripts.
  7. Monitor and Audit: Use logs to track how tokens are being used and watch for suspicious activity.

By internalizing these concepts, you are not just registering an application; you are building a robust security boundary that protects your users and your organization's data. As you continue to build, remember that identity is a moving target—stay updated with Microsoft’s latest documentation and security recommendations.


Not read yet

Frequently Asked Questions

Q: Can I change the token lifetime for only one specific app? A: Yes. Token lifetime policies are assigned to individual service principals. This allows you to have a strict policy for a high-security financial app and a more relaxed policy for an internal productivity tool within the same tenant.

Q: What happens if I lose my client secret? A: You should immediately revoke the old secret in the Azure portal and generate a new one. Update your application configuration to use the new secret. If you suspect the secret was compromised, treat all tokens issued during that time as potentially compromised.

Q: How do I know if my token is too large? A: If you notice "400 Bad Request" errors when calling your API, check the size of the Authorization header. If it exceeds 8KB, you likely have too many claims. Consider moving some claims to a database lookup or using groups instead of individual claims for roles.

Q: Should I use ID tokens to check if a user is logged in? A: You can use the presence of a valid ID token to determine if the user has an active session in the client UI, but do not use it to grant access to backend resources. Always rely on the Access Token for backend authorization.

Not read yet

Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.