JWT at the edge: verify once, trust a header

Validate the user's JWT once at API Gateway, pass identity downstream as a header, and close the bypass, spoofing and revocation gaps that design opens.

Published

Updated

Reading time

14 min

What is a backend allowed to believe? If the answer is "whatever the header says", then the security of the whole system has moved from cryptography to routing: the only question left is whether anything other than the gateway can reach the service. That is a legitimate trade, and often a good one, but it is only safe when you can name the mechanism that makes the gateway the sole door. This article takes one hypothetical system through that trade on Google Cloud: what the edge checks, what the services receive, what makes the header trustworthy, and what still breaks.

It leans on GCP IAM least privilege for the service-account side and on a generated OpenAPI spec for API Gateway for the config side.

The system under review#

Take a small product with a public API and three Cloud Run services behind it: orders, catalog and billing. Callers are browsers and mobile apps that sign in with Firebase Authentication and send the resulting ID token as a bearer token. The requirements that shape the design:

  • The services should not each need to know about the token issuer, its key set or its rotation.
  • Verification must not add a key download to every cold start.
  • One place should answer "which tokens are accepted", and one log line per rejection.
  • A compromised or misconfigured service must not be able to mint identity for the others.
  • Banning a user needs a defined, documented delay, not an accidental one.

Four places to verify, and what each one costs#

OptionWhat downstream receivesStrengthWeakness
Each service verifies the original token (for Firebase, the Admin SDK)The raw bearer tokenNo trust in the network path; services are independentVerification and key caching live in every service; versions of the library drift
Gateway verifies, passes claims in a headerClaims in a headerOne place for policy; service code is trivialEverything depends on the gateway being the only way in
Same, and the service also checks the caller is the gatewayClaims plus proof of originSpoofing needs the gateway identity, not just network reachService-to-service authentication must be set up
Gateway verifies, then mints a short-lived internal tokenA signed token with only the claims services needServices verify against a key set you controlYou now operate an issuer

For three services behind one gateway on Cloud Run, the third row falls out almost for free, because Cloud Run's own IAM check does the "is this the gateway" work before the request reaches the container. The fourth row is where I would go once a request hops through several services: a header forwarded across three services loses its guarantee, because service B can only believe what service A promises. The first row is the right answer whenever the gateway cannot be made the only door.

The token is verified once. The trusted zone is defined by who may call it, not by where it sits.

What the edge has to check#

Verifying a JWT is several checks, not one. RFC 8725, the JWT best current practices, lists the ones an edge verifier needs:

  • Algorithm (section 3.1). The verifier chooses the acceptable algorithms, never the token header. Use an allow-list and refuse none.
  • Issuer and audience (sections 3.8 and 3.9). A valid signature proves the token came from an issuer you trust. It does not prove the token was meant for you. Without an audience check, a token minted for another application of the same issuer is a valid login to yours.
  • Do not trust received claims (section 3.10). kid, jku and x5u are inputs to validate. A verifier never fetches keys from a URL the token names.
  • Explicit typing (sections 3.11 and 3.12). Tokens of different kinds that share an issuer must not be interchangeable. If you later add internal or refresh tokens, they must fail validation as access tokens.

The time claims come on top. exp, and where present nbf and iat, are checked with a small clock tolerance. A few seconds is enough; a tolerance of minutes quietly extends the life of every token you accept.

For Firebase ID tokens, the official verification guide gives the concrete values: the header carries alg RS256 and a kid, aud is the project ID, iss is https://securetoken.google.com/ followed by the project ID, sub is a non-empty string, and exp, iat and auth_time are consistent with now. The same page says that this verification does not check whether the token has been revoked. That sentence matters again in the failure section.

Configuring the gateway#

API Gateway can do all of that from the OpenAPI 2.0 spec. The JWT authentication guide and the Firebase variant give the syntax. The address and project values below are examples:

openapi2-edge.yamlyaml
swagger: "2.0"
info:
  title: orders-edge
  version: 1.0.0
schemes:
  - https
produces:
  - application/json
x-google-backend:
  address: https://orders-abc123def4-ew.a.run.app
securityDefinitions:
  firebase:
    authorizationUrl: ""
    flow: "implicit"
    type: "oauth2"
    x-google-issuer: "https://securetoken.google.com/my-project"
    x-google-jwks_uri: "https://www.googleapis.com/service_accounts/v1/metadata/x509/securetoken@system.gserviceaccount.com"
    x-google-audiences: "my-project"
security:
  - firebase: []
paths:
  /orders:
    get:
      operationId: listOrders
      responses:
        "200":
          description: The caller's orders
          schema:
            type: string

The x-google-backend extension names the backend, and the top-level security requirement applies the scheme to every operation.

The audience line deserves a sentence of its own. x-google-audiences is optional: when it is omitted, the gateway does not check against a list you supply and accepts JWTs whose aud is the backend service name, in the form https://SERVICE_NAME. A Firebase ID token carries the project ID as aud, so for Firebase you set it explicitly, as above. Setting it is also what makes the check visible in review, and a test that presents a token with the wrong aud and expects a rejection is the cheapest regression guard in this design.

Create the config and the gateway with a dedicated service account, which is the identity the gateway uses to call the backend:

terminalbash
gcloud api-gateway api-configs create edge-v1 \
  --api=orders-api --openapi-spec=openapi2-edge.yaml \
  --project=my-project \
  --backend-auth-service-account=gateway-invoker@my-project.iam.gserviceaccount.com
 
gcloud api-gateway gateways create orders-gw \
  --api=orders-api --api-config=edge-v1 \
  --location=europe-west1 --project=my-project

What the backend actually receives#

Three headers matter, and the OpenAPI 2.0 extensions reference and the JWT guide describe all of them:

  1. X-Apigateway-Api-Userinfo carries the authentication result: the JWT payload, base64url encoded. This is the header the services read.
  2. Authorization is replaced. With x-google-backend, the gateway obtains an ID token for itself, with the audience defaulting to the backend address unless you set jwt_audience, and sends that instead of the user's token. This is the proof that the request came through the gateway.
  3. X-Forwarded-Authorization holds the original value of Authorization. If the request arrived with a bearer token, the gateway copies it here before overriding the header. So the user's token does reach the service, as an unverified copy in a different header. A service that wants to re-verify it, or pass it on, can; a service that only needs identity should not touch it.

The service itself needs very little code. It decodes the userinfo header, checks the shape and refuses to continue without it:

src/identity.tsts
import type { NextFunction, Request, Response } from "express";
 
export interface Identity {
  sub: string;
  email?: string;
}
 
function decodeUserinfo(value: string): Identity | null {
  try {
    const claims = JSON.parse(Buffer.from(value, "base64url").toString("utf8"));
    if (typeof claims?.sub !== "string" || claims.sub.length === 0) return null;
    return {
      sub: claims.sub,
      email: typeof claims.email === "string" ? claims.email : undefined,
    };
  } catch {
    return null;
  }
}
 
export function requireIdentity(req: Request, res: Response, next: NextFunction): void {
  const header = req.header("x-apigateway-api-userinfo");
  const identity = header ? decodeUserinfo(header) : null;
  if (!identity) {
    res.status(401).json({ error: "missing_identity" });
    return;
  }
  res.locals.identity = identity;
  next();
}

It reads one header and fails closed. It keys on sub, never on the email, because emails change and can be reused. Mount it only on routes the gateway secures: a route exposed without a security requirement has no authentication result behind it, so a header on such a request is whatever the caller wrote. Public routes never read it.

Local development has no gateway, so my services carry a fallback that verifies the token directly when the forwarded header is absent. That is an alternate door, and alternate doors tend to stay unlocked. I constrained it to development and enforce that through configuration validation at startup, so the convenience path is unreachable in production by construction rather than merely unused.

Closing every other door#

The service accepts a header it cannot verify itself, so only the gateway may reach it. The securing backends guide says the gateway's service account needs roles/run.invoker, or a role containing run.routes.invoke, on the Cloud Run service. The other half is refusing everyone else:

terminalbash
gcloud run deploy orders \
  --image=europe-west1-docker.pkg.dev/my-project/apps/orders:2026-10-11 \
  --region=europe-west1 \
  --no-allow-unauthenticated \
  --service-account=orders-runtime@my-project.iam.gserviceaccount.com
 
gcloud run services add-iam-policy-binding orders \
  --region=europe-west1 \
  --member="serviceAccount:gateway-invoker@my-project.iam.gserviceaccount.com" \
  --role="roles/run.invoker"

Cloud Run performs the invoker check before the request reaches the container, so a direct call to the run.app URL with a user token, or with nothing, is refused at that layer. This is the boundary the whole design stands on. It is an IAM binding, which means it can be audited: list the invoker bindings on every service and alert on any change, in particular an allUsers member added "temporarily".

Restricting Cloud Run ingress is tempting as a second layer. The documented values are internal, internal-and-cloud-load-balancing and all, and the ingress page lists the Google Cloud services allowed to reach an internal service. API Gateway is not among them, so a service behind API Gateway keeps ingress at all and relies on the invoker role.

The comparison most readers will make: verify in the service#

With Firebase there is a second route that needs no gateway at all: each service calls the Admin SDK's verifyIdToken on the bearer token. It is a good answer for one or two services, and the SDK does the issuer, audience and algorithm checks for you:

src/verify-in-service.tsts
import { getAuth } from "firebase-admin/auth";
 
export async function userFromBearer(authorization: string | undefined) {
  const token = authorization?.startsWith("Bearer ") ? authorization.slice(7) : undefined;
  if (!token) return null;
  // The second argument also checks revocation, at the cost of a call to Firebase Auth.
  return getAuth().verifyIdToken(token, true);
}

Compared with the gateway design, you give up the single place that answers "which tokens are accepted", and every service carries the dependency and its upgrade schedule. You gain independence: nothing in this route depends on how the request arrived, so there is no bypass to close and no header to spoof. With the second argument set to true, you also get a revocation check that the gateway cannot give you, paid for with a network call. That trade is the real decision. If the number of services is small and the SDK is already there, I would verify in the service. The gateway starts to earn its place when services are written in different languages, when several teams ship them, or when you want rejections logged and rate-limited in one place.

If the edge is your own proxy#

Not every edge is API Gateway. A small Cloud Run proxy or an edge function does the same job with the jose library, and the discipline around it matters more than the dozen lines of verification: strip identity headers coming in, set them only after verification, and keep the key resolver at module scope so the cache survives between requests.

edge/verify.tsts
import { createRemoteJWKSet, jwtVerify, errors } from "jose";
import type { NextFunction, Request, Response } from "express";
 
const PROJECT_ID = "my-project";
const jwks = createRemoteJWKSet(
  new URL("https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com"),
  { timeoutDuration: 2000, cooldownDuration: 30_000, cacheMaxAge: 600_000 },
);
 
export async function verifyAtEdge(req: Request, res: Response, next: NextFunction): Promise<void> {
  // Never trust identity headers supplied by the client.
  delete req.headers["x-user-id"];
  delete req.headers["x-user-email"];
 
  const raw = req.header("authorization") ?? "";
  if (!raw.startsWith("Bearer ")) {
    res.status(401).json({ error: "missing_token" });
    return;
  }
 
  try {
    const { payload } = await jwtVerify(raw.slice(7), jwks, {
      issuer: `https://securetoken.google.com/${PROJECT_ID}`,
      audience: PROJECT_ID,
      algorithms: ["RS256"],
      clockTolerance: "5s",
      requiredClaims: ["sub", "exp", "iat"],
    });
    if (!payload.sub) throw new Error("empty subject");
    req.headers["x-user-id"] = payload.sub;
    if (typeof payload.email === "string") req.headers["x-user-email"] = payload.email;
    delete req.headers["authorization"]; // downstream never sees the raw token
    next();
  } catch (err) {
    if (err instanceof errors.JWKSTimeout) {
      res.status(503).json({ error: "keys_unavailable" });
      return;
    }
    res.status(401).json({ error: "invalid_token" });
  }
}

The JWK URL is the JSON Web Key Set endpoint for Firebase signing keys. It differs from the x509 URL in the gateway spec because jose consumes JWKs rather than PEM certificates. createRemoteJWKSet fetches when its cache is empty or stale and refetches on an unknown kid, but only after a cooldown, which defaults to 30 seconds. The maximum cache age defaults to 10 minutes and the request timeout to 5 seconds. Setting all three explicitly puts the behaviour in front of a reviewer instead of in library defaults.

The timeout case gets its own status. If the key endpoint is unreachable, the caller did nothing wrong, and a 401 tells a client to throw away a good session. A 503 says "try again".

What breaks under failure and change#

FailureWhy it happensContainment
Forged identity headerA path to the service that skips the gatewayInvoker role held only by the gateway; audit bindings; never read the header on open routes
Audience confusionaud unchecked or left at the defaultExplicit x-google-audiences; a wrong-audience test against a deployed staging gateway
Banned user keeps accessA verified token stays valid until exp; Google ID tokens last one hour and cannot be revokedA denylist of subjects the service checks, or verifyIdToken(token, true) on sensitive operations only; write the accepted delay down
Stale permissionsRoles in the token reflect the moment of issueKeep tokens to identity and look permissions up in the service
Key rotation or JWKS outageCache too long, or no cache at allBounded cache, refetch on unknown kid behind a cooldown, 503 on timeout
One bad config affects every serviceThe gateway is sharedReview spec changes like code; keep the previous API config so rollback is one command
Table 1— Failure modes of verify-once-at-the-edge and what contains each one

Two additions to that table. First, the revocation row follows from facts already quoted: the Firebase guide says its verification does not check revocation, and Google states that Google ID tokens are valid for one hour and cannot be revoked. Denylist entries only need to live as long as the token would have. I hit this myself during a beta: a freshly deleted test account could still write until its token expired. I did not shorten the token lifetime, because that is a blunt trade against sign-in friction. I accepted instead that a signature only answers "who signed this", not "does this account still exist and stand in good standing", and routed every security-relevant decision through one chokepoint that reads current account state.

Second, tests for the edge itself should include an expired token, a token from a different issuer, and tokens with alg set to none or to an HMAC algorithm. All must be rejected. Run them against a deployed staging gateway after every config change: a mock proves your code, and only the real gateway proves the config. Log rejections by reason class, never with the token. I also test the boundary route by route: a route whose security block is missing or wrong does not fail at the gateway, it forwards the request without an identity and the rejection finally happens deep inside a service with a confusing error. So for every route, an unauthenticated request must be rejected at the edge, and I assert the shape of that rejection instead of assuming it. The test felt redundant the day I wrote it.

Which side of the line your system falls on#

  • One or two services, Firebase tokens: verify in the service with the Admin SDK. A gateway adds a component, a config format and an outage source for no consolidation benefit.
  • Several services, Cloud Run only, one public API: the gateway design in this article, with the invoker role as the boundary and the audience set explicitly.
  • Services reachable by other front doors (queues, schedulers, other teams' clients): you cannot make the gateway the only entry, so verify the token wherever it lands, with one shared and well-tested library.
  • Requests that fan out across several internal hops: have the edge mint a short-lived internal token, with a lifetime of a minute or two, a distinct typ and one audience per target, and never forward the userinfo header.
  • Immediate revocation or fast-changing permissions: the edge check is not enough on its own, and the service has to consult state anyway.

The rule that holds across all five: verify the token completely in one place, make that place the only door, and let nothing behind it believe a header the door did not write.

Share
All articles →

A one-hour audit procedure for Google Cloud IAM: snapshot the policies, run eight targeted queries, triage what you find, and keep the result diffable.

13 min