envoy-guide
Module 6 · Real-world Recipes·18 min·intermediate

JWT authentication and external authorization

Verify JWTs in Envoy and delegate fine-grained policy to OPA via ext_authz.

Two filters, two jobs

Auth in Envoy splits cleanly:

  • jwt_authn — who is the caller? Verifies a JWT against a JWKS, checks issuer and audiences, optionally enforces required scopes. Local, fast, no external service call.
  • ext_authz — is this caller allowed to do this? Calls out to a separate policy service (OPA, your own sidecar) over HTTP or gRPC.

Most production gateways stack them: JWT first, then ext_authz with the parsed JWT claims forwarded as context.

jwt_authn — verify a JWT against a JWKS

YAML
          http_filters:
          - name: envoy.filters.http.jwt_authn
            typed_config:
              "@type": type.googleapis.com/envoy.extensions.filters.http.jwt_authn.v3.JwtAuthentication
              providers:
                idp:
                  issuer: https://auth.example.com/
                  audiences: ["mcp-api"]
                  remote_jwks:
                    http_uri:
                      uri: https://auth.example.com/.well-known/jwks.json
                      cluster: idp_jwks
                      timeout: 5s
                    cache_duration: { seconds: 600 }
                  forward: true                    # forward the JWT upstream
                  payload_in_metadata: jwt_payload # expose claims to other filters
              rules:
              - match: { prefix: "/v1/" }
                requires: { provider_name: idp }
              - match: { prefix: "/healthz" }      # public — no requires block

Key choices:

  • remote_jwks caches keys for 10 minutes by default. Don't lower this aggressively — your JWKS endpoint will get hammered.
  • forward: true keeps the JWT on the request when it hits your backend. Drop it (false) if you're terminating auth at Envoy and want backends to never see customer tokens.
  • payload_in_metadata: jwt_payload is what makes claims available to ext_authz later in the chain. Crucial.

ext_authz — call out for a policy decision

The classic pairing is OPA running as a sidecar. Envoy sends a CheckRequest (the request method, path, headers, optionally the body and the dynamic metadata from earlier filters); OPA returns OK or Denied.

YAML
          - name: envoy.filters.http.ext_authz
            typed_config:
              "@type": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthz
              transport_api_version: V3
              grpc_service:
                envoy_grpc: { cluster_name: opa_authz }
                timeout: 0.25s
              failure_mode_allow: false             # fail closed
              metadata_context_namespaces:
              - envoy.filters.http.jwt_authn        # forward JWT claims into the check

The metadata_context_namespaces line is the one that connects the two filters: the parsed JWT claims that jwt_authn stashed in metadata get serialized into the OPA CheckRequest. OPA can then write Rego like:

rego
default allow = false

allow if {
  input.attributes.metadata_context.filter_metadata
    ["envoy.filters.http.jwt_authn"]
    ["jwt_payload"]["scope"] == "tools:write"
  input.attributes.request.http.method == "POST"
  startswith(input.attributes.request.http.path, "/v1/tools")
}

No re-verifying JWTs in OPA. No extra HTTP hops. The signature was already checked once in C++.

When to use what

You need to…Reach for
Verify caller identity from a stateless tokenjwt_authn
Enforce coarse RBAC ("this scope can call this prefix")jwt_authn (with requires per route)
Enforce fine-grained policy ("user X on tenant Y can call tool Z")ext_authz (OPA / custom)
Support legacy auth (cookies, API keys)ext_authz only
Multi-step decision (auth → quota check → audit log)ext_authz

In a real gateway you'll have both, in this order: JWT first (cheap, local), ext_authz second (expensive, remote). That way an unauthenticated request never reaches OPA at all.

failure_mode_allow is a footgun

failure_mode_allow: true means "if the authz service is unreachable, let the request through." Sounds resilient — but it means a crashed OPA pod silently disables your security. Default to false (fail closed) and use circuit breakers + active health checks on the OPA cluster.

Hands-on: a verified token in five minutes

Hands-on · Local Keycloak + JWT + Envoy

We'll skip the OPA half this time and just prove jwt_authn works against a real IdP.

  1. Run a local Keycloak:
Shell
docker run --rm -d --name kc -p 8081:8080 \
  -e KEYCLOAK_ADMIN=admin -e KEYCLOAK_ADMIN_PASSWORD=admin \
  quay.io/keycloak/keycloak:latest start-dev
  1. In the Keycloak UI (http://localhost:8081): create realm demo, create client mcp-api, create user alice with a password.

  2. Configure Envoy with a jwt_authn filter pointed at Keycloak's JWKS: http://kc:8080/realms/demo/protocol/openid-connect/certs (use host.docker.internal if running Envoy in another container without --network host). Set issuer: http://localhost:8081/realms/demo and audiences: ["mcp-api"].

  3. Get a token via Keycloak's token endpoint:

Shell
TOKEN=$(curl -s -X POST \
  -d 'grant_type=password' -d 'client_id=mcp-api' \
  -d 'username=alice' -d 'password=YOUR_PASSWORD' \
  http://localhost:8081/realms/demo/protocol/openid-connect/token \
  | jq -r .access_token)
  1. Call your Envoy with and without the token:
Shell
curl -i localhost:10000/v1/anything                          # 401
curl -i -H "Authorization: Bearer $TOKEN" localhost:10000/v1/anything  # 200

The first one is rejected by jwt_authn before reaching the upstream. The second flies through.

Stripping the JWT downstream

For zero-trust backends: set forward: false on jwt_authn, then in ext_authz mutate the request to inject a signed internal header (x-internal-user) that backends trust. Customer tokens never leave Envoy. OPA can do this with the response.dynamic_metadata field.

Real-world example · A multi-tenant SaaS API gateway
Problem
End users authenticate with JWTs from Auth0. Service-to-service traffic uses internal API keys. Some routes are public; others require specific roles AND tenant membership. Hard-coding all this into every backend service is a maintenance nightmare.
Envoy solution
One Envoy gateway. jwt_authn handles the JWT path; an ext_authz sidecar (OPA) handles everything else — API key validation, role checks, tenant boundaries, even per-endpoint quotas. Backends only ever see a small set of trusted internal headers; the customer JWT is verified once at the edge and never re-parsed.

Up next

We've covered who and what they're allowed. Lesson 20 covers how much — rate limiting per-pod and globally per-tenant. After that, Lesson 21 stacks all five filters into the production-grade gateway.

Quick check

What's the cleanest way for an OPA ext_authz policy to read claims from a JWT that jwt_authn already verified?

Practical task
Finish the quick check and tick off the task to unlock.
Quick checkTasks 0/4