FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

API Security & OAuth2 PKCE

OAuth2 PKCE authorization flows, JWT verification, and scope enforcement.

Freshness: current•15 min read•Software and Web Engineering

Key Learning Outcomes

  • ✓Secure API endpoints with OAuth2 PKCE and JWT claims
  • ✓Enforce role-based access control contracts
Full Technical Reference Document

Mental model

OAuth 2.1 Authorization Code + PKCE (Proof Key for Code Exchange) secures user login across SPAs, mobile apps, and CLI/MCP agents without embedding static client secrets anywhere public code runs, while signed JWTs (JSON Web Tokens) let downstream microservices validate identity and permission scopes cryptographically offline using cached JWKS public keys. Security fails immediately if engineers overlook algorithm-confusion defenses, loose aud/iss validation, client-side localStorage XSS token theft, or missing short TTLs and revocation controls.

Client Generates Verifier & S256 Challenge
Auth Server Issues Short-Lived Auth Code
Exchange Code + Verifier for Access JWT
API Validates JWT Signature via JWKS
Route Enforces iss, aud & Scopes
Conceptual teaching model synthesized from:oauth-security-bcp,owasp-api-security

Theory

Under the OAuth 2.0 Security Best Current Practice (RFC 9700 / OAuth 2.1), legacy Implicit Flow (response_type=token leaking tokens directly into browser URL hashes and history logs) and Resource Owner Password Credentials (ROPC) are eliminated completely in favor of Authorization Code + PKCE (code_challenge_method=S256) paired with exact redirect-URI matching (state CSRF binding and OpenID Connect nonce).

Token ArchitectureSignature / Key ModelVerification SpeedImmediate Revocation StoryIdeal Deployment
Asymmetric JWT (RS256 / ES256 / EdDSA)Private key signs in Auth Server; services fetch public JWKS (kid)Sub-millisecond CPU verification (~0.05 ms), zero DB hitShort Access TTL (5–15 min) + optional Redis jti blocklist / Refresh RotationMulti-service APIs, MCP gateways, microservices verifying tokens at scale
Symmetric JWT (HS256)Shared secret across signer & every verifierVery fast HMACCompromising any verifier microservice leaks signing key for entire platform!Monoliths only where single service both mints and validates
Opaque Token + Introspection / BFF CookiesRandom high-entropy bearer string checked against Auth DB/Redis (RFC 7662)1 Redis/HTTP lookup per call (1–3 ms)Instant single-row delete / logout revocationBrowser sessions behind Backend-for-Frontend (HttpOnly, SameSite=Lax) cookies

Strict JWT Claim Verification and JWKS Rotation Hygiene

A valid cryptographic signature alone never guarantees authorization. Every microservice verifying an incoming bearer JWT must enforce four explicit gates via an explicit algorithm allowlist:

  1. Pin Exact algorithms=["ES256"] (or ["RS256"]): Never trust the untrusted token header's alg field unconditionally (blocking "alg": "none" or RSA-public-key-as-HMAC HS256 attacks).
  2. Validate iss (Issuer) and aud (Audience): Reject tokens minted by the same Identity Provider intended for a different downstream API audience (Confused Deputy token replay).
  3. Require exp and Enforce Bounded leeway (<= 30 s): Never accept infinite-lived tokens or missing exp claims.
  4. Refresh JWKS Safely on Unknown kid: Cache the provider's JSON Web Key Set in memory with rate-limited cache-miss refresh (min 60 s cooldown against bogus kid DoS floods) so key rotations succeed with zero downtime.
python
import jwt
from jwt import PyJWKClient
from fastapi import Depends, HTTPException, Security, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer, SecurityScopes
​
# PyJWKClient caches public keys by kid and throttles JWKS endpoint fetches cleanly
jwks_client = PyJWKClient("https://auth.fullstackaihub.com/.well-known/jwks.json", cache_jwk_set=True, lifespan=300)
bearer_scheme = HTTPBearer(auto_error=True)
​
EXPECTED_ISSUER = "https://auth.fullstackaihub.com"
EXPECTED_AUDIENCE = "https://api.fullstackaihub.com"
​
def verify_access_token(
security_scopes: SecurityScopes,
creds: HTTPAuthorizationCredentials = Security(bearer_scheme),
) -> dict:
try:
signing_key = jwks_client.get_signing_key_from_jwt(creds.credentials)
claims = jwt.decode(
creds.credentials,
signing_key.key,
algorithms=["ES256", "RS256"], # Explicit asymmetric allowlist only
issuer=EXPECTED_ISSUER,
audience=EXPECTED_AUDIENCE,
options={"require": ["exp", "iat", "sub", "iss", "aud"]},
leeway=15,
)
except jwt.ExpiredSignatureError:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Access token expired")
except jwt.PyJWTError:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid bearer token")
​
token_scopes = set(str(claims.get("scope", "")).split())
missing = [scope for scope in security_scopes.scopes if scope not in token_scopes]
if missing:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f"Missing required scopes: {', '.join(missing)}",
)
return claims

Alternatives and trade-offs

  • OAuth2 PKCE + BFF (HttpOnly SameSite Cookies for Web) + Short-Lived Bearer JWT for APIs/CLIs: Eliminates JavaScript token theft via XSS in browsers while allowing native mobile apps, CLI agents, and MCP tools to run standard PKCE loops; adds a lightweight BFF/session proxy for browser SPAs.
  • Direct SPA Token Storage (sessionStorage / Memory + Rotating Refresh Tokens): Simpler static CDN frontend deployment with no server BFF layer, yet any third-party script or XSS bug in the SPA gains direct access to active API tokens.
  • API Keys / mTLS for Service-to-Service Traffic: Machine workloads without user delegation often prefer short-lived OAuth2 client_credentials tokens or mutual TLS (SPIFFE) over user-interactive PKCE flows.

Failure modes and misconceptions

  1. Accepting Arbitrary JWTs Without Checking aud (Cross-API Replay): If both Billing Service and Analytics Service trust the same Identity Provider (iss), omitting strict audience= checks lets a compromised or over-scoped token issued for Analytics call sensitive Billing endpoints cleanly. Always bind unique aud identifiers per API boundary.
  2. Storing Long-Lived Access or Refresh Tokens in localStorage: Any injected dependency or XSS flaw can exfiltrate localStorage cleanly in one line of JS. Prefer HttpOnly; Secure; SameSite=Lax cookies via a BFF for browser sessions, or strict memory-only short-lived access tokens paired with HttpOnly refresh token rotation + reuse detection.
  3. Confusing Authentication (401 Signature Valid) with Authorization (403 Scope/Ownership): Checking verify_jwt_token alone proves who the caller is, NOT whether claims["sub"] owns /v1/projects/{project_id} (BOLA / OWASP API1:2023). Always enforce object-level ownership checks against authenticated sub / org_id inside every database query.
  4. Trusting Weak "plain" PKCE Mode or Skipping Exact redirect_uri Validation: Always enforce S256 (SHA-256) PKCE challenges (code_challenge_method=S256) and strict exact-string redirect_uri equality (never wildcard subdomain prefixes) to block authorization code interception.
Reflect before revealing the guide

Decision scenario

Your platform exposes REST endpoints, a browser-hosted Next.js dashboard, and a public Streamable HTTP MCP gateway accessed by CLI agents like Claude Code and Cursor. Authenticate browser users via OAuth 2.1 Authorization Code + PKCE (S256) terminated into encrypted HttpOnly; Secure; SameSite=Lax cookies, issue short-lived 5-minute ES256 JWT access tokens (aud="https://fullstackaihub.com/mcp") with rotating single-use refresh tokens (reuse detection revokes the full token family on replay!) for third-party MCP clients, validate iss/aud/exp/scope against rate-limited cached JWKS keys on every service request, and enforce tenant/object-level authorization inside every SQL query (WHERE workspace_id = :token_org).

Learning outcomes

  • Diagram OAuth 2.1 Authorization Code + PKCE (S256) end-to-end and explain how it prevents authorization code injection without client secrets.
  • Verify asymmetric JWTs (ES256 / RS256) safely using cached JWKS rotation, explicit algorithms, iss, aud, and exp requirements.
  • Defend against BOLA (API1:2023), localStorage XSS theft, and cross-service token replay.
  • Balance short-lived stateless JWTs with refresh token rotation and HttpOnly BFF cookie patterns.

Trade-offs

Asymmetric OAuth 2.1 PKCE + JWKS validation delivers high-throughput, horizontally scalable zero-DB-lookup authentication across APIs and third-party agents, balanced against short revocation latency windows (<= Access Token TTL), strict token storage security in browsers, and disciplined object-level authorization checks.

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-201Production LLM Engineer

Design an observable full-stack LLM product from capability validation through interfaces retrieval evaluation security and operations.

37 concepts~35h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next