← experimental
Contents
  1. Key Claims
  2. Definition
  3. Why It Matters
  4. API Keys
  5. OAuth2 Roles
  6. JSON Web Tokens (JWT)
  7. OAuth2 Grant Types
  8. Authorization Code
  9. Authorization Code + PKCE
  10. Client Credentials
  11. Device Authorization
  12. Scopes
  13. OIDC — OpenID Connect
  14. Refresh Tokens
  15. SAML 2.0
  16. Token Validation at the API Gateway
  17. How Different Sources Treat It
  18. Related Concepts

Key Claims

  • OAuth2 is authorisation, OIDC is authentication. OAuth2 lets a client get scoped access to a resource server; OIDC adds the ID token to assert who the user is. Treating them interchangeably is the most common implementation error.
  • ID tokens are never access tokens. Different aud claims (client vs resource server), different lifetimes, different semantics. Mixing them creates real privilege-escalation paths.
  • Match the grant to the client type. Authorization Code for server-side web apps; Authorization Code + PKCE for SPAs and mobile (public clients); Client Credentials for M2M; Device for input-constrained devices. Implicit grant is deprecated.
  • Access tokens are short-lived; refresh tokens rotate. 1-60 minute access token lifetimes limit theft damage; refresh tokens issued one-at-a-time with dual-use detection (revoke the family if a rotated token is reused).
  • API keys aren't OAuth2 substitutes. They can't represent user delegation. If a third party calls on behalf of a user, an API key forces credential sharing — the exact problem OAuth2 solves. Use Authorization Code or Client Credentials instead.
  • Scopes are coarse-grained authorisation. "Can write orders" is appropriate; "can write order #12345 owned by user 456" is RBAC/ABAC inside the service. Don't try to express resource-level access via scopes.
  • The API gateway is the canonical validation point. Signature check, claim validation (iss/aud/exp/nbf), scope enforcement, forward validated claims as trusted headers. Offloads crypto from every service and ensures consistent enforcement.

Definition

OAuth2 is an authorisation framework (RFC 6749) that allows a client to obtain limited access to a resource server on behalf of a resource owner, without sharing credentials. It is the foundation for API authentication and authorisation in modern distributed systems. OIDC (OpenID Connect) extends OAuth2 with an identity layer, enabling authentication as well as authorisation.

Why It Matters

APIs cannot be secured by network perimeters alone — in cloud and mobile environments, requests arrive from untrusted networks. OAuth2 provides a standard, auditable mechanism for verifying who is calling and what they are permitted to do, without embedding credentials in every service.

API Keys

API keys are a non-standard authentication mechanism commonly used for system-to-system calls or public API access (e.g. GitHub, Stripe). They are simpler than OAuth2 but provide no user delegation mechanism (→ Mastering Api Architecture Ch 7).

Security requirements for API keys: An API key must be cryptographically random — generated by a CSPRNG — and long enough to be unguessable. The typical standard is 32 characters (256 bits). Short or deterministic keys are vulnerable to enumeration.

Don't mix keys and users: When a third-party application uses an API key to call a service on behalf of a user, the service has no way to verify who the actual user is — it only knows the application's identity. Accepting both an API key (application identity) and user credentials (user identity) as separate inputs forces the user to share credentials with the third party, which is the problem OAuth2 was designed to solve. The correct answer is OAuth2 Client Credentials (for system-only calls) or Authorization Code (when acting on behalf of a user).

Avoid HTTP Basic: HTTP Basic sends credentials with every request. If a third-party application asks to access an API on a user's behalf, HTTP Basic requires handing over the username and password to that third party — exactly the credential-sharing problem OAuth2 eliminates. Do not permit HTTP Basic access to external APIs.

OAuth2 Roles

(→ Mastering Api Architecture Ch 7)

Role Description
Resource Owner The entity (typically a user) who controls access to the protected resource
Authorization Server (AS) Issues tokens after authenticating the resource owner and obtaining consent
Client The application requesting access on behalf of the resource owner
Resource Server The API that holds the protected resource and validates tokens

The authorization server and resource server are logically separate; in practice they may be operated by the same product (e.g. Keycloak, Auth0) but they serve different functions.

JSON Web Tokens (JWT)

JWTs are the standard token format for OAuth2 (→ Mastering Api Architecture Ch 7). They consist of three base64url-encoded parts: header, payload, signature.

Two forms:

Form Description Use
JWS (JSON Web Signature) Signed but readable — anyone can decode the payload Standard access token; claims are visible
JWE (JSON Web Encryption) Encrypted — payload cannot be read without the key When token contents are sensitive

JWS is the common form. The API gateway or resource server validates the signature using the AS's public key (fetched from the JWKS endpoint), verifying authenticity without contacting the AS per request.

Standard JWT Claims:

Claim Name Meaning
iss Issuer Identifies the AS that issued the token
sub Subject The entity the token represents (user ID or service ID)
aud Audience The intended recipient(s); resource server must validate this
exp Expiry Timestamp after which the token must be rejected
nbf Not Before Timestamp before which the token must not be accepted
iat Issued At Timestamp of issuance
jti JWT ID Unique identifier; enables token replay detection

Token lifetime: access tokens should be short-lived — 1 to 60 minutes — to limit the damage from token theft. Shorter lifetimes require more frequent token refresh but reduce the window of exposure if a token is compromised. Long-lived assertions have greater risk of theft or replay (NIST Digital Identity Guidelines).

Subject (sub) claim: should be a stable, unique identifier such as a UUID — not an email address or username, which users change over time. Consistency of the sub value is required for reliable user tracking across sessions.

OAuth2 Grant Types

Grant types define the flow by which a client obtains tokens. The correct grant depends on the nature of the client and whether a user is present (→ Mastering Api Architecture Ch 7):

Authorization Code

For confidential clients (server-side web apps) where client secrets can be kept private. Flow:

  1. Client redirects user to AS with response_type=code
  2. AS authenticates user, obtains consent, returns authorization code
  3. Client exchanges code for access token via back-channel request (code never exposed in browser)

This is the most secure flow for user-facing web applications.

Authorization Code + PKCE

For public clients — SPAs and mobile apps — where a client secret cannot be kept private. PKCE (Proof Key for Code Exchange, RFC 7636) replaces the client secret:

  1. Client generates a code_verifier (random string) and a code_challenge (SHA-256 hash)
  2. Code challenge is sent with the authorization request
  3. Code verifier is sent with the token exchange — AS verifies the hash matches

PKCE prevents authorization code interception attacks. It should be used by all public clients; the implicit grant (which skips the code exchange) is deprecated.

Client Credentials

For machine-to-machine (M2M) communication where no user is involved. The client authenticates directly with the AS using its client ID and secret and receives an access token for the system's own identity — not on behalf of any user.

This is the correct grant for service-to-service API calls in east–west traffic. Tokens should be cached and reused until near-expiry to avoid unnecessary AS load.

Device Authorization

For devices with limited input capabilities (IoT, smart TVs, CLIs). Flow:

  1. Device requests a device code and user code from AS
  2. User visits a URL on a separate device and enters the user code
  3. Device polls the AS until the user has authenticated

This grant is not common in typical API architectures but is important for IoT gateway scenarios.

Scopes

Scopes are strings that represent permissions requested by the client. They are:

  • Defined by the resource server (e.g. read:orders, write:payments)
  • Requested by the client in the authorization request
  • Presented to the resource owner on the consent screen
  • Included in the token; enforced by the API gateway or resource server

Scopes provide coarse-grained authorisation — they are suitable for broad capability grants ("can write orders") but not for fine-grained resource-level access ("can write order 12345 owned by user 456"). Fine-grained access control requires RBAC or ABAC logic inside the service.

OIDC — OpenID Connect

OIDC adds an identity layer on top of OAuth2 (→ Mastering Api Architecture Ch 7). The key addition is the ID token — a JWT that asserts identity (who the user is), as distinct from the access token (what the user is permitted to do).

Critical rule: ID tokens must never be used as access tokens, and access tokens must never be used as ID tokens. The audiences (aud claims) differ:

  • ID token aud: the client application
  • Access token aud: the resource server

OIDC also defines standard claims for user identity: name, email, phone_number, address, picture, and others. The /userinfo endpoint allows clients to fetch these claims separately.

Refresh Tokens

Refresh tokens are long-lived credentials that allow a client to obtain new access tokens without re-authenticating the user. They are:

  • Stored server-side or in a secure client store
  • Used only at the token endpoint (back-channel), never sent to resource servers
  • Subject to rotation — the AS issues a new refresh token with each use and invalidates the old one

Dual-use detection: if an AS receives a refresh token that has already been rotated (indicating it has been stolen and used by an attacker), it should immediately revoke the entire token family and require the user to re-authenticate.

SAML 2.0

SAML 2.0 is an older XML-based standard for enterprise SSO, commonly found in corporate identity providers (Active Directory Federation Services, Okta, Ping). The SAML 2.0 Profile for OAuth2 extension allows a SAML assertion to be used as an OAuth2 grant — enabling a client to exchange a SAML assertion for an OAuth2 access token. This is the standard integration pattern when an existing enterprise IdP must be connected to a modern OAuth2-based API platform.

Token Validation at the API Gateway

The API gateway is the canonical enforcement point for token validation in north–south traffic (→ Api Gateway). It should:

  1. Validate the JWT signature using the AS's JWKS endpoint (cached with periodic refresh)
  2. Validate iss, aud, exp, nbf claims
  3. Enforce scopes against the requested endpoint
  4. Forward validated claims (user ID, scopes, roles) to backend services as trusted headers

This offloads cryptographic validation from every service and ensures consistent enforcement at the perimeter.

For east–west traffic (service-to-service), the service mesh handles mutual TLS identity (Sidecar Service Mesh), but the Client Credentials grant is still used to carry application-level identity and scopes.

How Different Sources Treat It

Source Perspective
Mastering Api Architecture Comprehensive treatment of OAuth2, JWT, OIDC, all grant types, and refresh token security. Emphasises gateway enforcement and the ID token / access token distinction.
  • Api Gateway — enforces token validation and scope checking at the perimeter
  • Threat Modeling — OAuth2 mitigates STRIDE S (Spoofing) and E (Elevation of Privilege)
  • Zero Trust — OAuth2 is the application-layer component of a zero trust implementation
  • Sidecar Service Mesh — complements OAuth2 with mTLS for transport-layer identity in east–west traffic
  • Adrs — grant type selection and token lifetime decisions warrant ADRs