0
0
Microservicessystem_design~7 mins

Service-to-service authentication in Microservices - System Design Guide

Choose your learning style9 modes available
Problem Statement
When microservices communicate without verifying each other's identity, unauthorized services can access sensitive data or perform actions they shouldn't. This leads to security breaches, data leaks, and trust issues between services.
Solution
Service-to-service authentication ensures that each service proves its identity before accessing another service. This is done by exchanging secure tokens or certificates that confirm the caller is trusted, preventing unauthorized access and maintaining secure communication.
Architecture
┌───────────────┐          ┌───────────────┐
│   Service A   │          │   Service B   │
│ (Client)      │          │ (Server)      │
└──────┬────────┘          └──────┬────────┘
       │  Request with Token          │
       │────────────────────────────>│
       │                             │
       │       Validate Token        │
       │<────────────────────────────│
       │                             │
       │       Response Data         │
       │<────────────────────────────│

This diagram shows Service A sending a request with an authentication token to Service B. Service B validates the token before responding with data.

Trade-offs
✓ Pros
Prevents unauthorized services from accessing APIs, enhancing security.
Enables fine-grained access control between microservices.
Supports auditing and monitoring of service interactions.
Improves trust and accountability in distributed systems.
✗ Cons
Adds complexity to service communication with token management.
Requires infrastructure for issuing and validating tokens or certificates.
May introduce latency due to authentication checks on each request.
Use when multiple microservices communicate over a network and sensitive data or operations require protection, especially at scale beyond 1000 requests per second.
Avoid when services run in a fully trusted, isolated environment with no external access and minimal security requirements, or for very low-scale internal tools where overhead outweighs benefits.
Real World Examples
Netflix
Uses mutual TLS for service-to-service authentication to ensure only authorized microservices communicate within their cloud environment.
Google
Implements service accounts and OAuth tokens for secure authentication between microservices in Google Cloud Platform.
Uber
Uses JWT tokens for authenticating requests between microservices to prevent unauthorized access and ensure secure data flow.
Code Example
The before code shows a simple request without authentication, which is insecure. The after code adds JWT token generation in Service A and token validation in Service B, ensuring only authorized requests succeed.
Microservices
### Before: No service-to-service authentication
import requests

def call_service_b():
    response = requests.get('http://service-b/api/data')
    return response.json()

### After: Service-to-service authentication using JWT token
import requests
import jwt
import time

SECRET_KEY = 'shared-secret'

# Generate JWT token

def generate_token():
    payload = {'iss': 'service-a', 'exp': int(time.time()) + 60}
    token = jwt.encode(payload, SECRET_KEY, algorithm='HS256')
    return token

# Call Service B with token

def call_service_b():
    token = generate_token()
    headers = {'Authorization': f'Bearer {token}'}
    response = requests.get('http://service-b/api/data', headers=headers)
    return response.json()

# Service B validates token
from flask import Flask, request, jsonify
import jwt

app = Flask(__name__)

@app.route('/api/data')
def data():
    auth_header = request.headers.get('Authorization', '')
    if not auth_header.startswith('Bearer '):
        return jsonify({'error': 'Unauthorized'}), 401
    token = auth_header.split(' ')[1]
    try:
        jwt.decode(token, SECRET_KEY, algorithms=['HS256'])
    except jwt.ExpiredSignatureError:
        return jsonify({'error': 'Token expired'}), 401
    except jwt.InvalidTokenError:
        return jsonify({'error': 'Invalid token'}), 401
    return jsonify({'data': 'secure data'})
OutputSuccess
Alternatives
Network-level security (e.g., VPN, VPC)
Secures communication channels but does not authenticate individual services explicitly.
Use when: Choose when you need to secure the network perimeter but have trusted services inside the network.
API Gateway Authentication
Centralizes authentication at the gateway rather than between each service pair.
Use when: Choose when you want to simplify authentication by handling it at the edge before requests reach internal services.
Summary
Service-to-service authentication prevents unauthorized microservices from accessing APIs.
It uses tokens or certificates to verify each service's identity before communication.
This pattern is essential for secure, scalable microservice architectures.