Bird
Raised Fist0
Microservicessystem_design~7 mins

JWT token propagation in Microservices - System Design Guide

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Problem Statement
When a user makes a request to a microservices system, the initial authentication token must be trusted and passed along to downstream services. Without proper token propagation, downstream services cannot verify the user's identity or permissions, leading to security gaps or repeated authentication calls that increase latency and complexity.
Solution
JWT token propagation involves forwarding the original JWT token received from the client through each microservice call. Each service extracts the token from the request headers, validates it locally without needing to call the authentication server again, and uses the token claims to enforce authorization. This keeps the user context intact across service boundaries efficiently.
Architecture
┌─────────────┐      ┌─────────────┐      ┌─────────────┐
│   Client    │─────▶│  Service A  │─────▶│  Service B  │
│ (with JWT)  │      │ (validates  │      │ (validates  │
└─────────────┘      │  JWT token) │      │  JWT token) │
                     └─────────────┘      └─────────────┘

This diagram shows a client sending a request with a JWT token to Service A, which validates and forwards the same token to Service B for validation and authorization.

Trade-offs
✓ Pros
Reduces authentication server load by enabling local token validation in each service.
Maintains user identity and permissions consistently across microservices.
Improves performance by avoiding repeated authentication calls.
Simplifies authorization logic by using token claims directly.
✗ Cons
Requires all services to implement JWT validation logic correctly.
Token revocation is difficult since tokens are self-contained and stateless.
If token contains sensitive data, it must be securely signed and encrypted.
Use when microservices need to authenticate and authorize user requests independently at scale, especially when read traffic exceeds thousands of requests per second.
Avoid when tokens need frequent revocation or real-time permission changes, or when services cannot securely handle token validation.
Real World Examples
Netflix
Netflix propagates JWT tokens across its microservices to maintain user session context and permissions without central authentication calls, improving streaming performance.
Uber
Uber uses JWT token propagation to securely pass user identity and roles between services like ride matching and payment processing, ensuring consistent authorization.
Shopify
Shopify propagates JWT tokens in its microservices to allow independent services to validate user permissions for store management and order processing.
Code Example
The before code shows Service A calling Service B without forwarding the JWT token, so Service B cannot authenticate the user. The after code extracts the JWT token from the incoming request headers in Service A and forwards it to Service B. Service B then validates the token locally before processing the request, enabling secure token propagation.
Microservices
### Before: No token propagation, downstream service cannot authenticate

# Service A handler

def service_a_handler(request):
    # Process request without forwarding token
    response = call_service_b(request.data)
    return response


### After: Propagate JWT token in headers

# Service A handler

def service_a_handler(request):
    jwt_token = request.headers.get('Authorization')
    headers = {'Authorization': jwt_token} if jwt_token else {}
    response = call_service_b(request.data, headers=headers)
    return response

# Service B handler

def service_b_handler(request):
    jwt_token = request.headers.get('Authorization')
    if not validate_jwt(jwt_token):
        return {'error': 'Unauthorized'}, 401
    # Proceed with authorized request
    return {'data': 'success'}

# Helper function

def validate_jwt(token):
    # Simplified validation logic
    if token and token.startswith('Bearer '):
        # Decode and verify signature, expiry, etc.
        return True
    return False
OutputSuccess
Alternatives
OAuth 2.0 Token Introspection
Instead of propagating JWT tokens, each service calls a central authorization server to validate tokens on every request.
Use when: Choose when token revocation and real-time permission updates are critical and token validation must be centralized.
Session-based Authentication
User session state is stored centrally and services rely on session IDs instead of self-contained tokens.
Use when: Choose when maintaining server-side session state is acceptable and token statelessness is not required.
Summary
JWT token propagation forwards the user's authentication token across microservices to maintain identity and permissions.
Each service validates the token locally to avoid repeated calls to the authentication server.
This pattern improves performance and consistency but requires careful token management and validation.

Practice

(1/5)
1. What is the main purpose of JWT token propagation in a microservices architecture?
easy
A. To encrypt all communication between microservices
B. To store user data permanently in each microservice
C. To securely share user identity information across multiple services
D. To replace API keys for service-to-service authentication

Solution

  1. Step 1: Understand JWT token role

    JWT tokens carry user identity and claims securely in a compact form.
  2. Step 2: Identify propagation purpose

    Propagating JWT tokens allows each microservice to verify and trust the user's identity without storing it locally.
  3. Final Answer:

    To securely share user identity information across multiple services -> Option C
  4. Quick Check:

    JWT propagation = share identity securely [OK]
Hint: JWT tokens carry user identity for trust across services [OK]
Common Mistakes:
  • Confusing JWT propagation with data storage
  • Thinking JWT encrypts all communication
  • Assuming JWT replaces all authentication methods
2. Which HTTP header is commonly used to forward the JWT token between microservices?
easy
A. Authorization
B. X-Auth-Token
C. Cookie
D. Content-Type

Solution

  1. Step 1: Identify standard header for tokens

    The Authorization header is the standard way to send bearer tokens like JWT in HTTP requests.
  2. Step 2: Confirm other headers' roles

    X-Auth-Token is less standard, Cookie is for browser sessions, Content-Type defines data format.
  3. Final Answer:

    Authorization -> Option A
  4. Quick Check:

    JWT token sent in Authorization header [OK]
Hint: JWT tokens go in Authorization header as Bearer [OK]
Common Mistakes:
  • Using Cookie header for token forwarding
  • Confusing Content-Type with authentication headers
  • Assuming custom headers like X-Auth-Token are standard
3. Consider this code snippet in a microservice forwarding a JWT token:
fetch('http://serviceB/api', {
  headers: { 'Authorization': req.headers['authorization'] }
})
What will happen if the original request has no Authorization header?
medium
A. The Authorization header is set to an empty string
B. Service B receives an Authorization header with value 'undefined'
C. The fetch call throws an error and fails
D. Service B receives the request without any Authorization header

Solution

  1. Step 1: Check header forwarding code

    The code forwards req.headers['authorization'] directly as the Authorization header value.
  2. Step 2: Understand missing header behavior

    If req.headers['authorization'] is undefined, the header is omitted in fetch, so Service B gets no Authorization header.
  3. Final Answer:

    Service B receives the request without any Authorization header -> Option D
  4. Quick Check:

    Missing header means no Authorization sent [OK]
Hint: Undefined header means no header sent, not 'undefined' string [OK]
Common Mistakes:
  • Assuming 'undefined' string is sent as header value
  • Expecting fetch to throw error on missing header
  • Thinking header is set to empty string automatically
4. A microservice fails to verify JWT tokens from upstream services. Which of these is the most likely cause?
medium
A. The microservice does not forward the Authorization header
B. The microservice uses a different secret or public key to verify tokens
C. The microservice sends tokens in the request body instead of headers
D. The microservice caches tokens for too long

Solution

  1. Step 1: Analyze verification failure causes

    Verification fails if the microservice uses a wrong secret or public key to check the JWT signature.
  2. Step 2: Evaluate other options

    Not forwarding headers causes downstream issues, sending tokens in body is non-standard but not verification failure, caching affects freshness but not signature verification.
  3. Final Answer:

    The microservice uses a different secret or public key to verify tokens -> Option B
  4. Quick Check:

    Wrong key = verification fails [OK]
Hint: Verification needs matching secret/public key [OK]
Common Mistakes:
  • Confusing forwarding issues with verification errors
  • Assuming token location affects signature verification
  • Ignoring key mismatch as cause of failure
5. In a microservices system, Service A receives a JWT token from a user and calls Service B, which calls Service C. To ensure secure JWT token propagation and verification, which design is best?
hard
A. Service A sends the JWT to Service B, which forwards the same JWT to Service C; each service verifies the token locally
B. Service A sends the JWT to Service B; Service B generates a new token for Service C with its own secret
C. Service A sends the JWT only to Service B; Service B calls Service C without any token
D. Service A sends the JWT to Service B; Service B stores the token and Service C fetches it from Service B when needed

Solution

  1. Step 1: Understand token propagation best practice

    JWT tokens should be forwarded unchanged so each service can verify the original user identity and claims.
  2. Step 2: Evaluate alternatives

    Generating new tokens breaks trust chain; skipping tokens breaks authentication; fetching tokens from another service adds complexity and risk.
  3. Final Answer:

    Service A sends the JWT to Service B, which forwards the same JWT to Service C; each service verifies the token locally -> Option A
  4. Quick Check:

    Forward original JWT for trust and verification [OK]
Hint: Forward original JWT unchanged for trust across services [OK]
Common Mistakes:
  • Creating new tokens at intermediate services
  • Not forwarding tokens to all downstream services
  • Relying on token fetching instead of forwarding