API Gateways, Traffic Management & the Edge›05 · Authentication at the edge

Lesson 05 of 13 · Hands-on with Envoy Gateway

Authentication at the edge

Decide who is calling before a request reaches any service. Compare API keys, JWTs from an identity provider, client certificates and external authorization, then validate JWTs at the gateway hands-on: a stdlib-only token tool, a SecurityPolicy with issuer, audience and keys, real 401s for missing, invalid and tampered tokens, verified claims turned into headers, and proof that a forged tenant header is overwritten. Finish with what still belongs in the services.

Intermediate → Advanced
Key wordsedge authenticationAPI keysJWTJSON Web TokenOIDCJWKSissueraudiencesignatureRS256claimsclaimToHeadersSecurityPolicyEnvoy Gateway401 UnauthorizedWWW-Authenticateforged headersmTLS clientsexternal authorizationext_authzOPAauthentication vs authorization

Authenticate once, at the door

If every service checks credentials its own way, one of them will get it wrong. Checking at the gateway gives one implementation, one configuration and one log for "who called". Services still decide what the caller may do with their data.

  • Authentication: who are you? (the gateway's job)
  • Authorization: may you do this? (coarse rules at the gateway, fine-grained in the service)
Identity provider signs tokens Client app or browser Gateway verify signature, issuer, audience, expiry with the JWKS Service x-tenant-id: acme (from verified claims) sign in public keys (JWKS) Bearer token claims as headers missing, tampered or expired token → 401
The client gets a token from the identity provider and sends it with each request; the gateway verifies it with the provider's public keys and passes verified claims to the service.

At a concert, the ticket is printed by the box office with a special stamp nobody else can copy (a signed token). The door staff check the stamp, the date and the venue name (signature, expiry, audience), then put a coloured wristband on you (claims as headers). Inside, the VIP-area guard only looks at the wristband, and still decides whether you may go backstage (authorization in the service).

The options

Method Strength Weakness Typical use
API key in a header Simple for consumers A long-lived shared secret; leaks in logs and repos; no user identity Partner server-to-server calls, low-risk public APIs
JWT from an identity provider (OIDC) Signed, short-lived, carries identity and claims; verified without calling the IdP Revocation is hard until expiry; keep lifetimes short User-facing and service APIs
mTLS client certificate Strong machine identity, no secret in headers Certificate issuing and rotation B2B integrations, devices, internal edges
External authorization (ext_authz) Any logic: entitlements, policy-as-code (OPA), custom checks One more network call per request; must be highly available Complex or central policy

Many APIs combine them: mTLS for partners, JWT for users, an API key to identify the calling application for quotas.

Lab: JWT validation at the gateway

Use the cluster from lesson 4. Output is real (Envoy Gateway 1.10.0).

1. A token tool with no dependencies

In production, tokens come from your identity provider. For the lab, this script makes an RSA key, publishes the public part as a JWKS (JSON Web Key Set), and signs tokens. It needs only Python 3 and openssl.

#!/usr/bin/env python3
"""Lab helper: make an RSA key, its JWKS, and signed test tokens. Needs only python3 + openssl."""
import base64, json, subprocess, sys, time
from pathlib import Path

def b64u(b): return base64.urlsafe_b64encode(b).rstrip(b"=").decode()

key = Path("jwt-key.pem")
if not key.exists():
    subprocess.run(["openssl", "genrsa", "-out", str(key), "2048"], check=True, capture_output=True)

if sys.argv[1] == "jwks":
    mod = subprocess.run(["openssl", "rsa", "-in", str(key), "-noout", "-modulus"],
                         check=True, capture_output=True, text=True).stdout.strip().split("=", 1)[1]
    print(json.dumps({"keys": [{"kty": "RSA", "kid": "lab-1", "alg": "RS256", "use": "sig",
                                "n": b64u(bytes.fromhex(mod)), "e": b64u((65537).to_bytes(3, "big"))}]}))
else:  # token <tenant> [plan]
    tenant, plan = sys.argv[2], (sys.argv[3] if len(sys.argv) > 3 else "free")
    now = int(time.time())
    header = b64u(json.dumps({"alg": "RS256", "typ": "JWT", "kid": "lab-1"}).encode())
    claims = b64u(json.dumps({"iss": "https://idp.example.test", "aud": "orders-api", "sub": f"user@{tenant}",
                              "tenant": tenant, "plan": plan, "iat": now, "exp": now + 3600}).encode())
    sig = subprocess.run(["openssl", "dgst", "-sha256", "-sign", str(key)], input=f"{header}.{claims}".encode(),
                         check=True, capture_output=True).stdout
    print(f"{header}.{claims}.{b64u(sig)}")
$ python3 make-jwt.py jwks > jwks.json
$ T=$(python3 make-jwt.py token acme standard)
$ echo $T | cut -d. -f2 | tr '_-' '/+' | base64 -d
{"iss": "https://idp.example.test", "aud": "orders-api", "sub": "user@acme", "tenant": "acme",
 "plan": "standard", "iat": 1794161280, "exp": 1794164880

Anyone can read the payload: it's encoded, not encrypted. Never put secrets in claims.

2. A SecurityPolicy on the route

JWKS=$(cat jwks.json)
cat > jwt-policy.yaml <<EOF2
apiVersion: gateway.envoyproxy.io/v1alpha1
kind: SecurityPolicy
metadata:
  name: orders-jwt
  namespace: shop
spec:
  targetRefs:
  - { group: gateway.networking.k8s.io, kind: HTTPRoute, name: orders }
  jwt:
    providers:
    - name: lab-idp
      issuer: https://idp.example.test
      audiences: [ orders-api ]
      localJWKS:                 # lab only; in production use remoteJWKS (the IdP's JWKS URL)
        type: Inline
        inline: '$JWKS'
      claimToHeaders:            # pass verified claims to the backend
      - { claim: tenant, header: x-tenant-id }
      - { claim: plan,   header: x-tenant-plan }
EOF2
kubectl apply -f jwt-policy.yaml
$ kubectl get securitypolicy orders-jwt -n shop \
    -o jsonpath='{range .status.ancestors[*].conditions[*]}{.type}={.status} {.reason}{"\n"}{end}'
Accepted=True Accepted

3. Try every kind of caller

# No token
$ curl -si -H 'Host: api.example.test' localhost:8080/orders | grep -i -E '^HTTP|www-authenticate'
HTTP/1.1 401 Unauthorized
www-authenticate: Bearer realm="http://api.example.test/orders"

# Garbage token
$ curl ... -H "Authorization: Bearer abc.def.ghi" ...          → 401

# A real token whose payload was edited to say tenant globex (signature no longer matches)
$ curl ... -H "Authorization: Bearer $TAMPERED" ...            → 401

# A valid token for acme: the backend receives verified claims as headers
$ curl -s -H 'Host: api.example.test' -H "Authorization: Bearer $T" localhost:8080/orders
  "X-Tenant-Id": ["acme"], "X-Tenant-Plan": ["standard"], "Authorization": ["Bearer eyJhbGciOi..."]

# A valid acme token plus a forged header
$ curl -s -H 'Host: api.example.test' -H "Authorization: Bearer $T" -H 'x-tenant-id: globex' localhost:8080/orders
  "X-Tenant-Id": ["acme"], "X-Tenant-Plan": ["standard"]

The last test matters most: the backend can trust x-tenant-id because the gateway overwrote the client's value with the verified claim. Lesson 6 uses these headers for per-tenant rate limits, and the multi-tenant SaaS course uses the tenant claim for data isolation.

Only if every path goes through the gateway

A header set by the gateway is only trustworthy if clients can't reach the service another way. Block direct access with NetworkPolicy (only the gateway's namespace may call the service), or have the service verify the JWT itself as well.

What still belongs in the service

  • Fine-grained authorization: "may Ana approve invoice 42?" needs the invoice and Ana's roles.
  • Defence in depth: services can re-verify the JWT (cheap with cached keys) instead of trusting headers alone.
  • Audit: record who did what, with the user and tenant from the verified token.

Production notes

  • Use remoteJWKS pointing to the identity provider's JWKS URL; the gateway caches keys and picks up key rotation.
  • Keep access tokens short-lived (minutes); revoke sessions at the identity provider.
  • Validate aud: a token issued for another API must not work on yours.
  • Don't log full tokens; the lab's echo server shows one only to demonstrate.
  • Envoy Gateway's SecurityPolicy also supports API keys, basic auth, OIDC login for browser apps, CORS, IP allow/deny lists and external authorization.

Try it

  1. Make a token for audience billing-api (edit the script) and confirm it's rejected.
  2. Make a token that expired an hour ago and check the response.
  3. Add x-tenant-plan to a second route without the SecurityPolicy, send the header yourself, and explain why that route must not trust it.
  4. Rotate keys: generate a new key with a new kid, put both public keys in the JWKS, apply, and show that tokens signed with either key work.

Going deeper

  • Token exchange lets the gateway swap a user's token for a narrower one per backend, so services never see tokens meant for other APIs.
  • Sender-constrained tokens (mTLS-bound tokens or DPoP) make a stolen token useless on another client.
  • For identity concepts in depth (OIDC flows, workload identity, zero trust), see the Identity & Zero Trust course.

Recap

  • Authenticate once at the gateway; authorize coarse rules there and fine-grained rules in services.
  • JWTs are verified with the issuer's public keys: signature, issuer, audience and expiry.
  • Verified claims can become headers for backends; the gateway overwrites client-supplied values.
  • That trust only holds if services can't be reached around the gateway.

This site is a public version of my personal engineering knowledge hub. It intentionally excludes confidential company information and internal operational details.