JWT (JSON Web Token): Personal Journey with MS Entra Integration

Introduction

In my journey as a developer working with modern authentication systems, I've encountered numerous scenarios where understanding JWT (JSON Web Token) has been crucial. This post shares my personal experience and knowledge about JWT tokens, their integration with Microsoft Entra (formerly Azure AD), and practical Python implementations.

What is JWT (JSON Web Token)?

JWT is a compact, URL-safe means of representing claims to be transferred between two parties. Think of it as a digital passport that contains information about a user and can be verified without needing to contact the issuing authority every time.

JWT Structure

A JWT consists of three parts separated by dots (.):

eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.EkN-DOsnsuRjRO6BxXemmJDm3HbxrbRzXglbN2S4sOkopdU4IsDxTI8jO19W_A4K8ZPJijNLis4EZsHeY559a4DFOd50_OqgHs3PH-S7wRL0isHoN7vX-XvJ1VGH_8aS7XYQCmHQJL_OYTrOL_ZQ

1. Header

Contains metadata about the token:

{
  "alg": "RS256",
  "typ": "JWT",
  "kid": "key-id"
}

2. Payload (Claims)

Contains the actual data/claims:

3. Signature

Ensures the token hasn't been tampered with:

How JWT Works

From my experience implementing JWT-based authentication systems, here's how the flow typically works:

  1. User Authentication: User provides credentials to the Identity Provider (MS Entra)

  2. Token Issuance: MS Entra validates credentials and issues a JWT

  3. Token Usage: Client includes JWT in API requests

  4. Token Verification: API server validates the JWT signature and claims

  5. Access Decision: Based on token validity and claims, access is granted or denied

JWT Authentication Flow Diagram

The following sequence diagram illustrates the complete JWT authentication flow with MS Entra:

spinner

Authentication Flow Details

Phase 1: Initial Authentication

  • Steps 1-3: User provides credentials to the client application, which forwards them to MS Entra

  • Steps 4-5: MS Entra validates credentials and issues a JWT containing user claims

Phase 2: API Access with JWT

  • Step 6: Client includes JWT in the Authorization header (Bearer <token>)

  • Step 7: API server extracts the JWT from the request header

Phase 3: Token Validation

  • Steps 8-9: API server retrieves public keys from MS Entra's JWKS endpoint (cached for performance)

  • Steps 10-11: Server validates the JWT signature and verifies standard claims

  • Steps 12-14: Based on validation results, server either grants access or returns appropriate error codes

Phase 4: Token Refresh (When Needed)

  • Steps 15-18: When tokens expire, the refresh flow allows obtaining new tokens without re-authentication

Pros and Cons of JWT

Pros (From My Experience)

1. Stateless Authentication

  • No need to store session data on the server

  • Scales horizontally without session affinity

  • Perfect for microservices architecture

2. Cross-Domain Support

  • Works seamlessly across different domains

  • Ideal for Single Sign-On (SSO) implementations

  • Great for mobile and web applications

3. Rich Information Storage

  • Can contain user roles, permissions, and custom claims

  • Reduces database lookups for user information

  • Self-contained authorization data

4. Industry Standard

  • Widely supported across platforms and languages

  • RFC 7519 specification ensures consistency

  • Large ecosystem of libraries and tools

Cons (Lessons Learned)

1. Token Size

  • Larger than simple session IDs

  • Can impact network performance with many claims

  • HTTP header size limitations

2. Token Revocation Challenges

  • Cannot easily revoke tokens before expiration

  • Requires additional mechanisms for immediate revocation

  • Blacklisting adds complexity

3. Security Considerations

  • Sensitive data exposure if not properly secured

  • XSS vulnerabilities if stored in localStorage

  • Requires careful key management

4. Token Refresh Complexity

  • Need to handle token expiration gracefully

  • Refresh token implementation adds complexity

  • Clock skew issues between systems

MS Entra as Identity Provider

Microsoft Entra (formerly Azure AD) serves as an excellent Identity Provider for JWT-based authentication. Here's why I prefer it:

Key Benefits:

  • Enterprise Integration: Seamless integration with Microsoft ecosystem

  • Security Features: Multi-factor authentication, conditional access

  • Compliance: SOC 2, ISO 27001, and other certifications

  • Scalability: Handles millions of users and applications

MS Entra JWT Token Claims

Common claims in MS Entra tokens:

  • aud: Audience (your application ID)

  • iss: Issuer (MS Entra tenant)

  • sub: Subject (user identifier)

  • upn: User Principal Name

  • roles: Application roles

  • groups: Security groups

Python Implementation: Getting JWT from MS Entra

Here's a practical Python implementation I've used in production:

Prerequisites

First, install required packages:

1. Application Registration Setup

2. JWT Token Acquisition

3. JWT Token Validation and Claims Extraction

4. Application Integration Example

5. Usage Example

JWT Debugging and Validation Tools

During my development journey with JWT tokens, I've found several online tools invaluable for debugging, testing, and understanding JWT tokens. Here are the most useful ones:

1. JWT.io - The Primary JWT Debugger

JWT.ioarrow-up-right is the go-to tool for JWT debugging and is maintained by Auth0. Here's how I use it in my development workflow:

Key Features:

  • Token Decoding: Paste any JWT to see its decoded header, payload, and signature

  • Real-time Validation: Instantly see if a token is valid or expired

  • Algorithm Support: Supports all standard JWT algorithms (HS256, RS256, etc.)

  • Key Verification: Test signature validation with public/private keys

Practical Use Cases from My Experience:

A. Debugging MS Entra Tokens

B. Signature Verification

2. Other Useful JWT Tools

A. Token.dev

  • Speciality: Advanced JWT analysis with security insights

  • Best For: Security auditing and compliance checking

B. JWT Tool (Chrome Extension)

  • Feature: Browser-based JWT debugging

  • Best For: Debugging tokens directly in browser developer tools

C. Postman JWT Debugger

  • Feature: Built-in JWT debugging in Postman

  • Best For: API testing workflows with JWT authentication

3. Python Script for JWT Analysis

Here's a Python script I use for automated JWT analysis and validation:

4. Best Practices for JWT Debugging

Based on my experience, here are essential practices when working with JWT tokens:

A. Development Workflow

  1. Use jwt.io for immediate debugging when tokens don't work as expected

  2. Verify token structure matches your application's expectations

  3. Check expiration times to ensure tokens aren't expired during testing

  4. Validate audience and issuer claims match your application configuration

B. Production Debugging

  1. Never paste production tokens into online tools (security risk)

  2. Use local debugging tools or create sanitized test tokens

  3. Implement proper logging for token validation failures

  4. Monitor token usage patterns for anomalies

C. Security Considerations

5. Common JWT Issues and Debugging Tips

From my troubleshooting experience, here are common issues and how to debug them:

A. Token Validation Failures

B. Clock Skew Issues

C. Audience Mismatch

JWT Roles in Hybrid Identity: MS Entra and Microsoft ADFS Federation

In enterprise environments where both cloud (MS Entra) and on-premises (Microsoft ADFS) identity providers coexist, JWT tokens play a crucial role in managing user roles and permissions across different systems. From my experience implementing hybrid identity solutions, role management becomes particularly complex when users need consistent access rights regardless of which identity provider authenticates them.

Understanding Role Challenges in Hybrid Environments

In hybrid identity scenarios, roles and permissions can be defined in multiple places:

  • On-premises Active Directory (groups and roles)

  • MS Entra ID (application roles and groups)

  • ADFS claims (custom role mappings)

  • Application-specific roles (local role definitions)

The challenge is ensuring consistent role representation in JWT tokens regardless of the authentication source.

JWT Role Structure in Hybrid Identity

MS Entra Role Claims in JWT

ADFS Role Claims in JWT

Implementing Unified Role Management

Here's how I implement consistent role management across hybrid identity providers:

1. Role Mapping and Transformation

2. Role-Based Authorization Middleware

3. Flask Application with Hybrid Role Authorization

4. Role Synchronization Between Providers

Best Practices for JWT Roles in Hybrid Identity

From my experience implementing role management in hybrid environments:

1. Consistent Role Mapping

  • Create standardized role names across all providers

  • Maintain mapping tables between provider-specific and application roles

  • Use descriptive, business-meaningful role names

2. Hierarchical Role Structure

3. Role Caching Strategy

  • Cache role information to avoid repeated API calls

  • Implement cache invalidation when roles change

  • Set appropriate cache expiration times

4. Audit and Monitoring

  • Log all role-based access decisions

  • Monitor role assignments and changes

  • Alert on unusual role access patterns

5. Security Considerations

  • Validate role claims in JWT tokens

  • Implement principle of least privilege

  • Regular review and cleanup of role assignments

  • Secure role synchronization processes

This comprehensive approach to JWT roles in hybrid identity environments ensures consistent, secure, and manageable role-based access control across different identity providers and applications.

Best Practices from My Experience

1. Security

  • Always validate JWT signatures

  • Use HTTPS for all communications

  • Store tokens securely (avoid localStorage for sensitive apps)

  • Implement proper token expiration handling

2. Performance

  • Cache JWKS for signature validation

  • Use connection pooling for HTTP requests

  • Implement token caching with proper expiration

3. Error Handling

  • Graceful handling of token expiration

  • Proper error messages without exposing sensitive information

  • Fallback mechanisms for authentication failures

4. Monitoring

  • Log authentication events

  • Monitor token usage patterns

  • Alert on suspicious activities

Conclusion

JWT tokens with MS Entra provide a robust, scalable authentication solution. While they come with challenges like token size and revocation complexity, the benefits of stateless authentication and rich claim support make them ideal for modern applications.

The Python implementation demonstrated here provides a solid foundation for integrating JWT-based authentication in your applications. Remember to adapt the code to your specific security requirements and always follow the principle of least privilege when assigning roles and permissions.

In my experience, the key to successful JWT implementation is understanding the trade-offs and implementing proper security measures. MS Entra's robust infrastructure combined with careful implementation can provide enterprise-grade authentication for your applications.

Further Reading

Last updated