Bird
Raised Fist0
Microservicessystem_design~7 mins

Authentication at gateway level 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 each microservice handles authentication independently, it leads to duplicated code, inconsistent security policies, and increased latency. This scattered approach also makes it harder to update authentication mechanisms and increases the risk of security gaps across services.
Solution
Authentication at the gateway level centralizes the verification of user identity before requests reach any microservice. The gateway checks credentials or tokens once, then forwards authenticated requests downstream, reducing duplication and ensuring consistent security enforcement across all services.
Architecture
Client
API Gateway
Authentication
Authentication

This diagram shows the client sending requests to the API Gateway, which performs authentication checks before forwarding requests to microservices.

Trade-offs
✓ Pros
Centralizes authentication logic, reducing code duplication across microservices.
Ensures consistent security policies and easier updates to authentication mechanisms.
Improves performance by authenticating once at the gateway instead of multiple times.
Simplifies microservices, allowing them to focus on business logic.
✗ Cons
Introduces a single point of failure if the gateway is down or misconfigured.
Can become a performance bottleneck under very high traffic if not scaled properly.
Limits microservices' ability to perform fine-grained or service-specific authentication.
Use when you have multiple microservices requiring consistent authentication and want to reduce duplicated security code. Suitable for systems with moderate to high traffic where centralized control improves security management.
Avoid when microservices require highly customized or independent authentication logic, or when the gateway cannot be scaled to handle peak loads without latency.
Real World Examples
Netflix
Netflix uses an API gateway to authenticate user tokens centrally before routing requests to various microservices, ensuring consistent access control across their streaming platform.
Uber
Uber employs gateway-level authentication to validate user sessions once, reducing overhead and maintaining uniform security policies across their ride-hailing microservices.
Amazon
Amazon's API Gateway authenticates requests centrally, allowing their diverse microservices to trust the gateway's verification and focus on processing business logic.
Code Example
The before code shows each microservice checking the token, causing duplication. The after code moves authentication to the gateway, which checks the token once before forwarding requests. Microservices trust the gateway and do not perform authentication themselves.
Microservices
### Before: Authentication inside each microservice (naive)
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/data')
def data():
    token = request.headers.get('Authorization')
    if not token or token != 'valid-token':
        return jsonify({'error': 'Unauthorized'}), 401
    return jsonify({'data': 'secret data'})


### After: Authentication at API Gateway (centralized)
# Gateway code
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.before_request
def authenticate():
    token = request.headers.get('Authorization')
    if not token or token != 'valid-token':
        return jsonify({'error': 'Unauthorized'}), 401

@app.route('/proxy/<path:path>')
def proxy(path):
    # Forward request to microservice without auth check
    # (simplified example)
    return jsonify({'data': 'secret data from microservice'})

# Microservice code (no auth needed)
from flask import Flask, jsonify

microservice = Flask(__name__)

@microservice.route('/data')
def data():
    return jsonify({'data': 'secret data'})
OutputSuccess
Alternatives
Authentication at each microservice
Each microservice independently verifies user credentials or tokens, duplicating authentication logic.
Use when: Choose when microservices require distinct authentication rules or operate in highly isolated environments.
Service mesh with mutual TLS
Authentication is handled at the network layer between services using mutual TLS, focusing on service-to-service trust rather than user authentication.
Use when: Choose when securing service-to-service communication is the priority, alongside or instead of user authentication.
Summary
Authentication at the gateway centralizes user verification to avoid duplicated logic in microservices.
This approach ensures consistent security policies and simplifies microservice design.
However, it introduces a single point of failure and may limit service-specific authentication needs.

Practice

(1/5)
1. What is the main benefit of performing authentication at the gateway level in a microservices architecture?
easy
A. It slows down the request processing by adding extra steps.
B. It allows each microservice to handle its own authentication independently.
C. It eliminates the need for authorization in microservices.
D. It centralizes authentication, reducing repeated checks in each microservice.

Solution

  1. Step 1: Understand the role of gateway authentication

    Authentication at the gateway means checking user identity once before requests reach microservices.
  2. Step 2: Identify benefits of centralizing authentication

    This reduces repeated authentication logic inside each microservice, improving maintainability and security.
  3. Final Answer:

    It centralizes authentication, reducing repeated checks in each microservice. -> Option D
  4. Quick Check:

    Centralized authentication = It centralizes authentication, reducing repeated checks in each microservice. [OK]
Hint: Gateway authentication centralizes checks, avoiding repetition [OK]
Common Mistakes:
  • Thinking each microservice should authenticate independently
  • Confusing authentication with authorization
  • Assuming gateway authentication slows down system
2. Which of the following is the correct way to implement authentication at the gateway level?
easy
A. The gateway validates user tokens and forwards requests with user info.
B. The gateway forwards requests without checking authentication.
C. Each microservice validates user tokens independently.
D. Microservices share a database to authenticate users directly.

Solution

  1. Step 1: Identify gateway's role in token validation

    The gateway should validate user tokens to confirm identity before forwarding requests.
  2. Step 2: Understand forwarding with user info

    After validation, the gateway forwards requests including user identity details for downstream services.
  3. Final Answer:

    The gateway validates user tokens and forwards requests with user info. -> Option A
  4. Quick Check:

    Gateway validates tokens = The gateway validates user tokens and forwards requests with user info. [OK]
Hint: Gateway validates tokens, then forwards requests with user info [OK]
Common Mistakes:
  • Letting microservices validate tokens independently
  • Not validating tokens at the gateway
  • Using shared database for authentication in microservices
3. Consider this simplified request flow code snippet at the gateway:
function handleRequest(request) {
  const token = request.headers['Authorization'];
  if (!validateToken(token)) {
    return { status: 401, message: 'Unauthorized' };
  }
  return forwardRequest(request);
}
What will happen if validateToken always returns false?
medium
A. All requests will be forwarded to microservices.
B. Requests without tokens will be forwarded, others rejected.
C. All requests will be rejected with 401 Unauthorized.
D. Gateway will crash due to invalid token handling.

Solution

  1. Step 1: Analyze the token validation condition

    If validateToken(token) returns false, the code returns 401 Unauthorized immediately.
  2. Step 2: Determine effect on all requests

    Since it always returns false, no requests pass validation, so all are rejected with 401.
  3. Final Answer:

    All requests will be rejected with 401 Unauthorized. -> Option C
  4. Quick Check:

    Always false validation = 401 rejection [OK]
Hint: False validation means all requests rejected [OK]
Common Mistakes:
  • Assuming requests are forwarded despite failed validation
  • Thinking gateway crashes on invalid token
  • Ignoring the immediate return on failed validation
4. A gateway is designed to authenticate requests but sometimes forwards unauthorized requests to microservices. What is the most likely cause?
medium
A. The gateway does not check the token before forwarding.
B. The gateway caches old valid tokens and skips validation.
C. The gateway uses synchronous token validation.
D. Microservices override the gateway authentication.

Solution

  1. Step 1: Identify why unauthorized requests pass

    If the gateway caches tokens and skips validation, expired or revoked tokens may be accepted.
  2. Step 2: Understand caching impact on authentication

    Cached tokens can cause stale validation results, allowing unauthorized requests through.
  3. Final Answer:

    The gateway caches old valid tokens and skips validation. -> Option B
  4. Quick Check:

    Token caching causes stale auth = The gateway caches old valid tokens and skips validation. [OK]
Hint: Stale token cache causes unauthorized forwarding [OK]
Common Mistakes:
  • Assuming microservices override gateway auth
  • Ignoring token caching effects
  • Confusing synchronous validation with forwarding issues
5. You are designing a microservices system with authentication at the gateway level. To ensure high availability and avoid a single point of failure, which design approach is best?
hard
A. Deploy multiple gateway instances behind a load balancer with shared session storage.
B. Use a single gateway instance with a backup database for tokens.
C. Let each microservice authenticate independently to avoid gateway failure.
D. Disable authentication at the gateway and rely on microservices.

Solution

  1. Step 1: Identify high availability needs for gateway

    Multiple gateway instances prevent downtime if one fails, improving reliability.
  2. Step 2: Understand role of load balancer and shared session storage

    Load balancer distributes requests; shared session storage keeps authentication state consistent across gateways.
  3. Final Answer:

    Deploy multiple gateway instances behind a load balancer with shared session storage. -> Option A
  4. Quick Check:

    Multiple gateways + load balancer = high availability [OK]
Hint: Use multiple gateways with load balancer for reliability [OK]
Common Mistakes:
  • Relying on single gateway instance only
  • Ignoring session consistency across gateways
  • Disabling gateway authentication entirely