Zero Trust Service Auth Mock in Python

A simple HMAC-based token issuance and validation mock that enforces zero trust between microservices.

Medium Python 3.9+ Aug 9, 2026 Microservices patterns 10 views 0 copies

Python code

60 lines
Python 3.9+
import hmac
import hashlib
import json
import time

class ZeroTrustAuth:
    def __init__(self, secret_key):
        self.secret_key = secret_key
        self.service_tokens = {}

    def issue_token(self, service_name, ttl=300):
        payload = {
            "service": service_name,
            "issued_at": int(time.time()),
            "expires_at": int(time.time()) + ttl
        }
        token = hmac.new(
            self.secret_key.encode(),
            json.dumps(payload, sort_keys=True).encode(),
            hashlib.sha256
        ).hexdigest()
        self.service_tokens[token] = payload
        return token

    def validate_request(self, service_name, token):
        if token not in self.service_tokens:
            return False
        
        payload = self.service_tokens[token]
        if payload["service"] != service_name:
            return False
            
        if time.time() > payload["expires_at"]:
            del self.service_tokens[token]
            return False
            
        # Zero trust: verify every request cryptographically
        expected = hmac.new(
            self.secret_key.encode(),
            json.dumps(payload, sort_keys=True).encode(),
            hashlib.sha256
        ).hexdigest()
        
        return hmac.compare_digest(expected, token)


if __name__ == "__main__":
    auth = ZeroTrustAuth("shared-secret-key")
    
    # Service A requests a token
    token_a = auth.issue_token("payments-service", ttl=60)
    
    # Legitimate request from Service A
    print(f"Valid request from Service A: {auth.validate_request('payments-service', token_a)}")
    
    # Forged/spoofed request from Service B using Service A's token
    print(f"Spoofed request from Service B: {auth.validate_request('inventory-service', token_a)}")
    
    # Invalid token
    print(f"Invalid token: {auth.validate_request('payments-service', 'fake-token')}")

Output

stdout
Valid request from Service A: True
Spoofed request from Service B: False
Invalid token: False

How it works

The ZeroTrustAuth class issues a token by signing a JSON payload (service name and timestamps) with HMAC-SHA256 using a shared secret. Validation recomputes the expected HMAC and compares it securely with hmac.compare_digest, which prevents timing attacks. Token expiration is enforced by checking the expires_at field. The service name in the payload must match the requesting service, simulating a zero trust model where every request is authenticated and authorized independently.

Common mistakes

  • Sending the shared secret with each request instead of using the token.
  • Not deleting expired tokens from the store, causing memory leaks.
  • Using plain string comparison instead of `hmac.compare_digest` for token verification.

Variations

  1. Use `hashlib` with a random salt per service for additional security.
  2. Replace the in-memory dictionary with Redis for distributed token storage.

Real-world use cases

  • Internal microservices authenticate each other with short-lived HMAC tokens instead of trusting the network.
  • A service mesh issues signed tokens for service-to-service calls, rejecting expired or forged credentials.
  • CI/CD pipelines use similar HMAC-based tokens to authorize build agents against deployment endpoints.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Microservices patterns

Related tutorials and quizzes for this topic.