Apply Microservices Security
Implement mutual TLS between services, propagate user identity via JWT without leaking service-to-service credentials to clients, and enforce per-service authorization — preventing lateral movement within the service mesh when any single service is compromised.
Why This Is Best Practice
Adopted by: OWASP Microservices Security Cheat Sheet (2023) is the primary reference. NIST SP 800-204 (Security Strategies for Microservices) is the federal guidance. Google's BeyondProd (2019) describes their production microservices security model, which underpins Google Cloud's security design. Netflix, Uber, and Lyft all use Istio or Envoy-based service meshes with mTLS for service-to-service authentication. All major service mesh implementations (Istio, Linkerd, Consul Connect) provide mTLS as their primary security feature.
Impact: In a microservices architecture, services typically communicate over the internal network without authentication — any compromised container on the internal network can make arbitrary API calls to any service. The 2019 Capital One breach involved lateral movement from a compromised EC2 instance to S3 — the equivalent attack in microservices would be a compromised service accessing other services' data. Netflix's chaos engineering found that 80% of theoretical attack paths in their microservices architecture relied on unauthenticated internal service calls. mTLS eliminates this attack class by requiring cryptographic proof of service identity on every call.
Why best: Network segmentation (VPCs, security groups) provides perimeter security but doesn't authenticate services within the perimeter. mTLS provides cryptographic service identity — every service proves it is who it claims to be on every call. This enables zero-trust within the service mesh: even if an attacker compromises the network, they cannot make authenticated API calls without a valid service certificate.
Sources: OWASP Microservices Security Cheat Sheet; NIST SP 800-204; Google BeyondProd whitepaper (2019); Netflix Istio adoption guide
Steps
Enable mTLS between services with Istio:
# Istio PeerAuthentication — require mTLS in production namespace
apiVersion: security.istio.io/v1beta1
kind: PeerAuthentication
metadata:
name: default
namespace: production
spec:
mtls:
mode: STRICT # reject any plaintext connections
---
# DestinationRule — enforce mTLS when calling payment service
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
name: payment-service-mtls
namespace: production
spec:
host: payment-service.production.svc.cluster.local
trafficPolicy:
tls:
mode: ISTIO_MUTUAL # use Istio-managed certs
Propagate user identity via JWT without service credentials:
# API Gateway validates external JWT, issues internal service token
import jwt
from datetime import datetime, timedelta
INTERNAL_SECRET = get_secret("/production/internal-jwt-secret")
EXTERNAL_JWKS_URL = "https://auth.company.com/.well-known/jwks.json"
def gateway_auth_middleware(request):
# Step 1: Validate external user JWT
external_token = request.headers.get("Authorization", "").removeprefix("Bearer ")
try:
user_claims = verify_external_jwt(external_token, EXTERNAL_JWKS_URL)
except Exception:
return Response(401, "Unauthorized")
# Step 2: Issue internal service token with user context
# Internal token has shorter TTL and is not exposed to clients
internal_token = jwt.encode({
"sub": user_claims["sub"], # user ID
"email": user_claims["email"],
"roles": user_claims["roles"],
"iat": datetime.utcnow(),
"exp": datetime.utcnow() + timedelta(minutes=5), # short TTL
"iss": "api-gateway",
"aud": "internal",
}, INTERNAL_SECRET, algorithm="HS256")
# Forward to downstream services
request.headers["X-Internal-Token"] = internal_token
request.headers["X-User-ID"] = user_claims["sub"]
# Remove original token — downstream services don't need external JWT
del request.headers["Authorization"]
return forward_to_service(request)
Enforce per-service authorization with Istio AuthorizationPolicy:
# Only order-service can call payment-service — no other service should
apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
name: payment-service-policy
namespace: production
spec:
selector:
matchLabels:
app: payment-service
rules:
- from:
- source:
principals:
# Only order-service's service account
- "cluster.local/ns/production/sa/order-service"
to:
- operation:
methods: ["POST"]
paths: ["/v1/payments/charge"]
# Deny everything else — default deny
Validate and extract user context in each service:
# Each downstream service validates the internal token
import jwt
from functools import wraps
def require_internal_auth(f):
@wraps(f)
def decorated(request, *args, **kwargs):
token = request.headers.get("X-Internal-Token")
if not token:
return Response(401, "Missing internal auth token")
try:
claims = jwt.decode(
token,
INTERNAL_SECRET,
algorithms=["HS256"],
audience="internal",
issuer="api-gateway",
)
except jwt.ExpiredSignatureError:
return Response(401, "Token expired")
except jwt.InvalidTokenError as e:
logger.warning(f"Invalid internal token: {e}")
return Response(401, "Invalid token")
# Attach user context to request for authorization checks
request.user_id = claims["sub"]
request.user_roles = claims["roles"]
return f(request, *args, **kwargs)
return decorated
@require_internal_auth
def get_order(request, order_id: str):
order = Order.get(order_id)
# Authorization: user can only access their own orders
if order.user_id != request.user_id and "admin" not in request.user_roles:
return Response(403, "Forbidden")
return Response(200, order.to_dict())
Secure service-to-service calls without user context (background jobs):
# Service-to-service token for internal calls without a user (cron jobs, event processing)
def get_service_token(calling_service: str, target_service: str) -> str:
return jwt.encode({
"sub": calling_service,
"aud": target_service,
"iat": datetime.utcnow(),
"exp": datetime.utcnow() + timedelta(minutes=5),
"iss": "service-auth",
"type": "service", # distinguish from user tokens
}, SERVICE_SECRET, algorithm="HS256")
# Or: use workload identity / SPIFFE (via Istio) for automatic service tokens
# No code needed — Istio provides X.509 SVIDs automatically to each workload
Rules
- mTLS in PERMISSIVE mode (Istio default) allows plaintext — switch to STRICT before going to production.
- Internal tokens must have short TTLs (≤5 minutes) and must not be cached beyond that window — they're disposable credentials for a single request chain.
- Services must never accept the original client Authorization header as proof of internal identity — attackers who steal a user JWT can impersonate that user to all downstream services if there's no internal token.
- AuthorizationPolicy default action is ALLOW in Istio without a policy — explicitly deploy deny-by-default policies before adding allow rules.
Common Mistakes
- Sharing a single JWT signing key across all services — compromise of any service exposes the key; use asymmetric keys (RS256) so services can verify tokens without being able to mint them.
- Forwarding the client's JWT to downstream services directly — the client JWT has a long TTL and broad scope; create short-lived internal tokens scoped to the specific downstream call.
- No service-to-service authorization (only authentication) — verifying that a call comes from payment-service doesn't mean payment-service should be able to access user-service's admin endpoints; add operation-level authorization.
- Not rotating service certificates — Istio automatically rotates certificates every 24 hours; if using manual mTLS, implement automatic rotation with ≤90 day certs.
1---2name: apply-microservices-security3description: Use when building microservices that communicate with each other — implementing service-to-service mTLS, JWT propagation for user identity, and API gateway authentication to prevent lateral movement between services.4source: 'OWASP Microservices Security Cheat Sheet (owasp.org/www-project-cheat-sheets); NIST SP 800-204 (Microservices Security); Netflix Zuul/Istio documentation; Google BeyondProd whitepaper'5tags: [security, owasp, microservices, mtls, jwt, service-mesh, api-gateway, developer]6metadata:7 source: https://skillmd.com/skills/jeffreytse/apply-microservices-security8---910# Apply Microservices Security1112Implement mutual TLS between services, propagate user identity via JWT without leaking service-to-service credentials to clients, and enforce per-service authorization — preventing lateral movement within the service mesh when any single service is compromised.1314## Why This Is Best Practice1516**Adopted by:** OWASP Microservices Security Cheat Sheet (2023) is the primary reference. NIST SP 800-204 (Security Strategies for Microservices) is the federal guidance. Google's BeyondProd (2019) describes their production microservices security model, which underpins Google Cloud's security design. Netflix, Uber, and Lyft all use Istio or Envoy-based service meshes with mTLS for service-to-service authentication. All major service mesh implementations (Istio, Linkerd, Consul Connect) provide mTLS as their primary security feature.17**Impact:** In a microservices architecture, services typically communicate over the internal network without authentication — any compromised container on the internal network can make arbitrary API calls to any service. The 2019 Capital One breach involved lateral movement from a compromised EC2 instance to S3 — the equivalent attack in microservices would be a compromised service accessing other services' data. Netflix's chaos engineering found that 80% of theoretical attack paths in their microservices architecture relied on unauthenticated internal service calls. mTLS eliminates this attack class by requiring cryptographic proof of service identity on every call.18**Why best:** Network segmentation (VPCs, security groups) provides perimeter security but doesn't authenticate services within the perimeter. mTLS provides cryptographic service identity — every service proves it is who it claims to be on every call. This enables zero-trust within the service mesh: even if an attacker compromises the network, they cannot make authenticated API calls without a valid service certificate.1920Sources: OWASP Microservices Security Cheat Sheet; NIST SP 800-204; Google BeyondProd whitepaper (2019); Netflix Istio adoption guide2122## Steps23241. **Enable mTLS between services with Istio**:2526 ```yaml27 # Istio PeerAuthentication — require mTLS in production namespace28 apiVersion: security.istio.io/v1beta129 kind: PeerAuthentication30 metadata:31 name: default32 namespace: production33 spec:34 mtls:35 mode: STRICT # reject any plaintext connections36 ---37 # DestinationRule — enforce mTLS when calling payment service38 apiVersion: networking.istio.io/v1beta139 kind: DestinationRule40 metadata:41 name: payment-service-mtls42 namespace: production43 spec:44 host: payment-service.production.svc.cluster.local45 trafficPolicy:46 tls:47 mode: ISTIO_MUTUAL # use Istio-managed certs48 ```49502. **Propagate user identity via JWT without service credentials**:5152 ```python53 # API Gateway validates external JWT, issues internal service token54 import jwt55 from datetime import datetime, timedelta5657 INTERNAL_SECRET = get_secret("/production/internal-jwt-secret")58 EXTERNAL_JWKS_URL = "https://auth.company.com/.well-known/jwks.json"5960 def gateway_auth_middleware(request):61 # Step 1: Validate external user JWT62 external_token = request.headers.get("Authorization", "").removeprefix("Bearer ")63 try:64 user_claims = verify_external_jwt(external_token, EXTERNAL_JWKS_URL)65 except Exception:66 return Response(401, "Unauthorized")6768 # Step 2: Issue internal service token with user context69 # Internal token has shorter TTL and is not exposed to clients70 internal_token = jwt.encode({71 "sub": user_claims["sub"], # user ID72 "email": user_claims["email"],73 "roles": user_claims["roles"],74 "iat": datetime.utcnow(),75 "exp": datetime.utcnow() + timedelta(minutes=5), # short TTL76 "iss": "api-gateway",77 "aud": "internal",78 }, INTERNAL_SECRET, algorithm="HS256")7980 # Forward to downstream services81 request.headers["X-Internal-Token"] = internal_token82 request.headers["X-User-ID"] = user_claims["sub"]83 # Remove original token — downstream services don't need external JWT84 del request.headers["Authorization"]85 return forward_to_service(request)86 ```87883. **Enforce per-service authorization with Istio AuthorizationPolicy**:8990 ```yaml91 # Only order-service can call payment-service — no other service should92 apiVersion: security.istio.io/v1beta193 kind: AuthorizationPolicy94 metadata:95 name: payment-service-policy96 namespace: production97 spec:98 selector:99 matchLabels:100 app: payment-service101 rules:102 - from:103 - source:104 principals:105 # Only order-service's service account106 - "cluster.local/ns/production/sa/order-service"107 to:108 - operation:109 methods: ["POST"]110 paths: ["/v1/payments/charge"]111 # Deny everything else — default deny112 ```1131144. **Validate and extract user context in each service**:115116 ```python117 # Each downstream service validates the internal token118 import jwt119 from functools import wraps120121 def require_internal_auth(f):122 @wraps(f)123 def decorated(request, *args, **kwargs):124 token = request.headers.get("X-Internal-Token")125 if not token:126 return Response(401, "Missing internal auth token")127128 try:129 claims = jwt.decode(130 token,131 INTERNAL_SECRET,132 algorithms=["HS256"],133 audience="internal",134 issuer="api-gateway",135 )136 except jwt.ExpiredSignatureError:137 return Response(401, "Token expired")138 except jwt.InvalidTokenError as e:139 logger.warning(f"Invalid internal token: {e}")140 return Response(401, "Invalid token")141142 # Attach user context to request for authorization checks143 request.user_id = claims["sub"]144 request.user_roles = claims["roles"]145 return f(request, *args, **kwargs)146 return decorated147148 @require_internal_auth149 def get_order(request, order_id: str):150 order = Order.get(order_id)151 # Authorization: user can only access their own orders152 if order.user_id != request.user_id and "admin" not in request.user_roles:153 return Response(403, "Forbidden")154 return Response(200, order.to_dict())155 ```1561575. **Secure service-to-service calls without user context (background jobs)**:158159 ```python160 # Service-to-service token for internal calls without a user (cron jobs, event processing)161 def get_service_token(calling_service: str, target_service: str) -> str:162 return jwt.encode({163 "sub": calling_service,164 "aud": target_service,165 "iat": datetime.utcnow(),166 "exp": datetime.utcnow() + timedelta(minutes=5),167 "iss": "service-auth",168 "type": "service", # distinguish from user tokens169 }, SERVICE_SECRET, algorithm="HS256")170171 # Or: use workload identity / SPIFFE (via Istio) for automatic service tokens172 # No code needed — Istio provides X.509 SVIDs automatically to each workload173 ```174175## Rules176177- mTLS in PERMISSIVE mode (Istio default) allows plaintext — switch to STRICT before going to production.178- Internal tokens must have short TTLs (≤5 minutes) and must not be cached beyond that window — they're disposable credentials for a single request chain.179- Services must never accept the original client Authorization header as proof of internal identity — attackers who steal a user JWT can impersonate that user to all downstream services if there's no internal token.180- AuthorizationPolicy default action is ALLOW in Istio without a policy — explicitly deploy deny-by-default policies before adding allow rules.181182## Common Mistakes183184- **Sharing a single JWT signing key across all services** — compromise of any service exposes the key; use asymmetric keys (RS256) so services can verify tokens without being able to mint them.185- **Forwarding the client's JWT to downstream services directly** — the client JWT has a long TTL and broad scope; create short-lived internal tokens scoped to the specific downstream call.186- **No service-to-service authorization (only authentication)** — verifying that a call comes from payment-service doesn't mean payment-service should be able to access user-service's admin endpoints; add operation-level authorization.187- **Not rotating service certificates** — Istio automatically rotates certificates every 24 hours; if using manual mTLS, implement automatic rotation with ≤90 day certs.