Free Ebook cover API Gateways for Beginners: Managing, Securing, and Scaling Web APIs

API Gateways for Beginners: Managing, Securing, and Scaling Web APIs

New course

12 pages

Authentication at the Gateway: API Keys, JWT, and OAuth2 Basics

Capítulo 3

Estimated reading time: 10 minutes

+ Exercise

Gateway-level authentication as a first security layer

An API gateway commonly sits at the edge of your system and is a good place to enforce authentication before requests reach internal services. This gives you a consistent entry policy: every request must prove “who is calling” (identity) and, often, “what they are allowed to do” (access). Authentication at the gateway does not replace authorization inside services, but it reduces exposure by blocking unauthenticated traffic early and standardizing how identity information is passed downstream.

Identity vs access: what you are proving

Identity (authentication)

Identity answers: “Which client or user is this?” Examples: a mobile app user, a backend job, a partner integration, or an internal service. At the gateway, identity is typically established by checking a credential (API key, token) presented in a header.

Access (authorization)

Access answers: “Is this identity allowed to perform this action on this resource?” Gateways often do basic access control (for example, require a scope/role claim for certain routes), but fine-grained checks (resource ownership, business rules) usually belong in upstream services.

Why separate them

  • You can authenticate a caller (know who they are) but still deny access (not allowed to call this endpoint).
  • You can apply different access rules per route while using the same identity mechanism.
  • You can forward identity context to upstreams so they can make business-level authorization decisions.

Mechanism 1: API keys (identification and simple access control)

An API key is a shared secret string issued to a client. It is most often used to identify the calling application (not an end-user) and to apply coarse controls like rate limits, quotas, and basic allow/deny rules.

How API keys are typically sent

  • Header (recommended): X-API-Key: <key> or Authorization: ApiKey <key>
  • Query string (avoid if possible): ?api_key=<key> because URLs can leak via logs, browser history, and referrers.

What the gateway does with an API key

  • Extracts the key from the configured location (header).
  • Looks it up in a key store (gateway config, database, or external service).
  • Checks status (active/disabled), expiration/rotation metadata, and optionally allowed IPs or allowed routes.
  • Associates the request with a “client identity” (client_id/app_id) for logging, quotas, and forwarding.

Step-by-step: implementing API key auth at the gateway

  • Step 1: Decide the header name and enforce it consistently (for example, X-API-Key).
  • Step 2: Create a key registry with metadata: key, client_id, status, optional expires_at, optional allowed_scopes or allowed routes.
  • Step 3: Configure the gateway to reject requests missing the key (HTTP 401) and reject invalid/disabled keys (HTTP 401 or 403 depending on your policy).
  • Step 4: Attach identity context for upstreams (for example, set X-Client-Id to the resolved client id).
  • Step 5: Add rate limits/quotas keyed by client_id (often paired with API keys).

Practical example: request and forwarded context

GET /v1/reports HTTP/1.1
Host: api.example.com
X-API-Key: 9f2c...ab

If valid, the gateway may forward:

Continue in our app.

You can listen to the audiobook with the screen off, receive a free certificate for this course, and also have access to 5,000 other free online courses.

Or continue reading below...
Download App

Download the app

GET /v1/reports HTTP/1.1
Host: reports.internal
X-Client-Id: partner-123
X-Auth-Method: api-key

When API keys fit (and when they don’t)

  • Good for server-to-server integrations, partner access, internal tools, and simple identification.
  • Not ideal for end-user authentication because keys are long-lived and do not represent a user session.
  • If a key leaks, anyone can use it until you revoke/rotate it.

Mechanism 2: JWT validation (signature, claims, expiry)

A JWT (JSON Web Token) is a compact token format commonly used as a bearer token: whoever has it can use it. JWTs are often used as access tokens (and sometimes ID tokens in OpenID Connect). A gateway can validate JWTs locally by verifying the signature and checking claims, without calling a database for every request.

JWT structure in one minute

  • Header: token type and signing algorithm (for example, RS256).
  • Payload (claims): information like subject/user id, issuer, audience, scopes/roles, and timestamps.
  • Signature: proves the token was issued by a trusted party and not modified.

What the gateway should validate

  • Signature verification: verify with the correct key (shared secret for HS256, public key for RS256/ES256).
  • Issuer (iss): ensure the token came from the expected issuer.
  • Audience (aud): ensure the token is meant for your API (or a specific resource identifier).
  • Expiry (exp) and not-before (nbf): reject expired or not-yet-valid tokens.
  • Optional: subject (sub) presence, token id (jti) format, and required claims.
  • Optional access control: check scopes/roles claim for route-level requirements.

Step-by-step: configuring JWT validation at the gateway

  • Step 1: Decide where tokens are presented (commonly Authorization: Bearer <jwt>).
  • Step 2: Configure trusted issuer(s) and expected audience(s).
  • Step 3: Configure how to obtain verification keys: static key, or JWKS URL (JSON Web Key Set) for rotating public keys.
  • Step 4: Configure claim checks: require exp, enforce clock skew tolerance (for example, 1–2 minutes), and require specific scopes for protected routes.
  • Step 5: Decide what identity context to forward to upstreams (for example, user id and scopes) and how (headers).

Practical example: validating and forwarding JWT context

Client request:

GET /v1/orders HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...

After validation, the gateway may forward selected claims (not the whole token) to upstreams:

GET /v1/orders HTTP/1.1
Host: orders.internal
X-User-Id: 42
X-User-Scopes: orders:read
X-Auth-Method: jwt

Forward only what upstreams need. Treat forwarded headers as trusted only if they can only be set by the gateway (see “token forwarding rules” below).

Common JWT pitfalls to avoid

  • Accepting tokens without verifying signature (never do this).
  • Not checking iss and aud, allowing tokens from other environments or apps.
  • Using very long-lived access tokens; prefer short-lived tokens and refresh mechanisms (often handled by OAuth2/OIDC).
  • Blindly forwarding the entire JWT to every upstream when not necessary.

Mechanism 3: OAuth2 and OpenID Connect basics (authorization server, scopes, tokens)

OAuth2 is a framework for delegated authorization: it lets a client obtain an access token to call an API. OpenID Connect (OIDC) builds on OAuth2 to add standardized user authentication and identity tokens (ID tokens). In many real systems, the gateway validates OAuth2-issued JWT access tokens, but the concepts are worth separating: OAuth2 is the flow and roles; JWT is a token format.

Key roles and components

  • Resource owner: the user (in user-facing scenarios).
  • Client: the app calling the API (web app, mobile app, backend service).
  • Authorization server: issues tokens after authenticating the user and/or client (often an identity provider).
  • Resource server: the API being called (your gateway + upstream services).

Scopes and consent

Scopes are strings that represent permissions (for example, orders:read, orders:write). The authorization server issues tokens containing scopes, and the gateway can enforce that certain routes require certain scopes.

Common token types you’ll see

  • Access token: presented to the API; should be short-lived; may be JWT or opaque.
  • Refresh token: used by the client to get new access tokens; should not be sent to APIs; keep it off the gateway path.
  • ID token (OIDC): represents the authenticated user to the client application; not meant for authorizing API calls unless your design explicitly does so (typically you use the access token for APIs).

How a gateway validates OAuth2/OIDC tokens

There are two common patterns:

  • JWT access tokens: the gateway validates locally (signature + claims + scopes), often using the authorization server’s JWKS endpoint for public keys.
  • Opaque access tokens: the gateway calls the authorization server’s introspection endpoint to check if the token is active and what scopes/subject it has. This adds network latency but allows immediate revocation checks.

Step-by-step: enforcing scopes at the gateway (beginner pattern)

  • Step 1: Define scopes for your API operations (for example, orders:read for GET, orders:write for POST/PUT/DELETE).
  • Step 2: Configure the authorization server to issue those scopes to approved clients/users.
  • Step 3: Configure the gateway route policy: require orders:read on GET /v1/orders, require orders:write on POST /v1/orders.
  • Step 4: On each request, validate the token and check that required scopes are present; if not, return HTTP 403.
  • Step 5: Forward identity context (subject, scopes, client id) to upstreams for auditing and deeper authorization.

Forwarding identity context to upstreams (headers and trust boundaries)

After authenticating a request, the gateway often forwards a small set of identity attributes to upstream services so they don’t need to re-parse tokens for every call. This can simplify services, but it must be done carefully.

Typical headers to forward

  • X-User-Id or X-Subject: from sub claim (user identifier).
  • X-Client-Id: OAuth2 client id or API key owner id.
  • X-Scopes or X-Roles: normalized permissions.
  • X-Auth-Method: api-key, jwt, oauth2 for debugging/auditing.
  • X-Request-Id: correlation id for tracing (if you use it).

Token forwarding rules (important)

  • Do not trust incoming identity headers from the public internet. Configure the gateway to strip/overwrite headers like X-User-Id, X-Scopes, X-Client-Id on inbound requests, then set them itself after authentication.
  • Forward the original Authorization header only when necessary. If upstreams do not need the raw token, remove it to reduce leakage risk.
  • If you must forward tokens, forward only to services that require them, over TLS, and avoid logging them.
  • Keep a clear boundary: upstream services should treat gateway-injected headers as trusted only when requests can only reach them through the gateway (network controls, private subnets, mTLS, firewall rules).

Choosing the right method (client type, risk, and operational needs)

API keys

  • Best for: machine clients, partner integrations, low-to-medium risk endpoints, quick onboarding.
  • Pros: simple, easy to rotate, good for quotas and basic access control.
  • Cons: typically long-lived; weaker for user-level identity; leakage impact can be high if not rotated/restricted.

JWT validation

  • Best for: high-throughput APIs where local validation avoids per-request database calls; systems with an identity provider issuing JWTs.
  • Pros: fast validation, contains claims for context, works well with stateless services.
  • Cons: revocation is harder (unless short-lived tokens or additional checks); requires careful claim validation and key rotation handling.

OAuth2/OIDC

  • Best for: user-facing apps (web/mobile), third-party delegated access, and when you need standardized flows and consent.
  • Pros: mature ecosystem, scopes, short-lived access tokens + refresh tokens, supports multiple client types.
  • Cons: more moving parts (authorization server, flows, token management); opaque tokens may require introspection calls.

Quick decision guide

  • If the caller is a backend job or partner system and you mainly need identification + quotas: start with API keys, add IP allowlists and rotation.
  • If you need user identity and permissions in a standardized way: OAuth2/OIDC with access tokens (often JWT) validated at the gateway.
  • If you already have JWTs and need fast edge validation: validate JWTs at the gateway, enforce iss/aud/exp, and use scopes/roles for route-level checks.

Secure handling of secrets and tokens

API key and client secret handling

  • Store keys/secrets in a secrets manager or encrypted store; avoid hardcoding in gateway config repositories.
  • Rotate keys regularly and support multiple active keys during rotation windows.
  • Restrict keys by IP ranges, allowed routes, or allowed scopes when possible.
  • Never log API keys; mask them in access logs and traces.

JWT/OAuth2 token handling

  • Enforce TLS end-to-end from client to gateway; prefer TLS from gateway to upstreams as well.
  • Do not log bearer tokens. Configure log scrubbing for the Authorization header.
  • Keep access tokens short-lived; rely on refresh tokens at the client side (not sent to the API).
  • Use JWKS and key rotation; cache JWKS with reasonable TTL and handle key rollover gracefully.

Now answer the exercise about the content:

In a gateway setup that forwards identity context to upstream services, which practice best prevents clients from spoofing user identity headers (for example, X-User-Id or X-Scopes)?

You are right! Congratulations, now go to the next page

You missed! Try again.

Identity headers from the public internet must not be trusted. The gateway should remove/overwrite them on inbound requests, then inject verified identity attributes only after authentication.

Next chapter

Authorization and Policy Enforcement: Roles, Scopes, and Least Privilege

Arrow Right Icon
Download the app to earn free Certification and listen to the courses in the background, even with the screen off.