Skip to content

Security Guide: REST API Protection with OAuth2 & JWT

CoreConceptAugust 3, 20269 min read

Securing modern REST APIs against unauthorized access, credential interception, and session hijacking requires strict protocol standards. Legacy session-based cookies bound to monolith application servers struggle to scale across distributed microservices and decoupled single-page application (SPA) frontends.

OAuth 2.0 provides an industry-standard authorization framework delegating user consent, while JSON Web Tokens (JWT) offer self-contained, cryptographically signed security assertions. This guide explores OAuth2 grant types, Authorization Code Flow with PKCE, RS256 asymmetric signature verification, and secure refresh token rotation.

OAuth2 and JWT security architecture pillars
OAuth2 and JWT security architecture pillars

Mental Model: OAuth2 Roles & Token-Based Authentication

The OAuth 2.0 specification separates authentication architecture into four core roles: the Resource Owner (end user), the Client Application (SPA frontend or mobile app), the Authorization Server (Identity Provider issuing tokens), and the Resource Server (REST API endpoint protecting user data).

A JSON Web Token (JWT) contains three base64url-encoded parts separated by dots: a Header (specifying algorithm and key ID), a Payload (containing claims like sub, iss, exp, and custom roles), and a Signature verifying payload integrity.

Because JWTs are self-contained, Resource Servers verify incoming API request signatures (Authorization: Bearer <token>) statelessly without making database or network calls back to the Authorization Server. For related security patterns, review secure mongodb rbac and oauth2 pkce vs client credentials flow.

OAuth2 PKCE authorization code exchange and RS256 JWT signature verification sequence
OAuth2 PKCE authorization code exchange and RS256 JWT signature verification sequence

Quick reference

  • Separates roles into Resource Owner, Client, Authorization Server, and Resource Server.
  • JWT contains Header, Payload (claims), and Cryptographic Signature.
  • Stateless signature verification allows API servers to validate requests without DB lookups.
  • Standard claims include sub (subject ID), iss (issuer URI), exp (expiration timestamp), and aud (audience).
  • Never place sensitive passwords or un-encrypted PII inside base64url-encoded JWT payloads.

Remember this

Use stateless JWT access tokens for API request verification across distributed microservices.

Authorization Code Flow with PKCE for SPA & Mobile Apps

Public clients (Single-Page Applications and native mobile apps) cannot securely store client secret credentials due to exposed source code and decompilation risks.

The Authorization Code Flow with Proof Key for Code Exchange (PKCE) secures public client authentication against authorization code interception attacks.

The client generates a random Code Verifier string, derives a SHA-256 hash (Code Challenge), and redirects the user to the Authorization Server with the challenge. Upon user login, the Authorization Server returns a short-lived authorization code. The client exchanges the authorization code alongside the original un-hashed Code Verifier for JWT tokens, proving that the same client initiated the request.

Quick reference

  • PKCE protects public clients (SPAs, mobile apps) without requiring client secret storage.
  • Client generates random Code Verifier and SHA-256 hashed Code Challenge.
  • Authorization Server verifies that Code Verifier matches Code Challenge before issuing tokens.
  • Prevents malicious browser extensions or URI schemes from stealing authorization codes.
  • Deprecated legacy Implicit Grant flows in favor of Authorization Code with PKCE.

Remember this

Mandate Authorization Code Flow with PKCE for all SPA and mobile application authentications.

Cryptographic Signing: RS256 Asymmetric Keys vs HS256 Symmetric Secrets

Signing JWTs guarantees that payload claims have not been tampered with in transit. Algorithms fall into two categories: HS256 (HMAC with SHA-256) and RS256 (RSA Signature with SHA-256).

HS256 uses a single shared secret key for both signing and verifying tokens. If a Resource Server requires key access to verify incoming requests, compromising that server exposes the signing secret, allowing an attacker to forge arbitrary administrative tokens.

RS256 uses asymmetric key pairs. The Authorization Server holds the private key to sign JWTs, while Resource Servers use the public key to verify signatures. Identity Providers publish public keys via a standard JWKS (JSON Web Key Set) endpoint (/.well-known/jwks.json), enabling instant verification across multi-cloud services.

OAuth2 PKCE authorization code exchange and RS256 JWT signature verification sequence
OAuth2 PKCE authorization code exchange and RS256 JWT signature verification sequence

Quick reference

  • HS256 symmetric signing uses a single shared secret for both signing and verification.
  • RS256 asymmetric signing uses a private key for signing and public keys for verification.
  • JWKS endpoints (/.well-known/jwks.json) distribute public verification keys dynamically.
  • Resource Servers cache JWKS public keys locally to verify JWT signatures in sub-milliseconds.
  • Enforce strict alg verification in API gateways to prevent 'alg: none' JWT signature bypass exploits.

Remember this

Sign production JWTs using RS256 asymmetric key pairs and expose public verification keys via JWKS.

Token Revocation, Refresh Token Rotation, & Blacklisting

Because JWT access tokens are validated statelessly, revoking a compromised access token before its expiration window requires operational planning.

Set short access token lifespans (e.g., 5 to 15 minutes) to minimize exposure windows. Combine short-lived access tokens with long-lived Refresh Tokens stored in HttpOnly, SameSite=Strict browser cookies.

Implement Refresh Token Rotation. Every time a client exchanges a refresh token for a new access token, issue a new refresh token and invalidate the old one. If a revoked refresh token is reused, immediately invalidate all refresh tokens in that family to isolate credential theft.

Quick reference

  • Short-lived access tokens (15-minute expiry) restrict vulnerability windows upon token leak.
  • Store refresh tokens in HttpOnly, Secure, SameSite=Strict cookies to block XSS theft.
  • Refresh Token Rotation invalidates old refresh tokens upon every exchange request.
  • Detecting reused refresh tokens revokes the entire token family automatically.
  • Maintain a low-latency Redis token revocation blacklist for emergency session terminations.

Remember this

Pair short-lived RS256 access tokens with Refresh Token Rotation in HttpOnly cookies.

Key takeaway

To test JWT security, attempt modifying the payload sub claim of an RS256 token in jwt.io. Send the modified token to your API and verify that signature verification rejects the request with a 401 Unauthorized error.

Share:

Related Articles

Selecting the correct authorization flow is essential for securing modern applications. The OAuth 2.1 specification cons

Read

JSON Web Tokens are a common access-token format, but OAuth 2.0 does not require them: providers may issue opaque bearer

Read

You log out and the admin panel still accepts the old token. Or you build "Sign in with Google" and accidentally treat a

Read

Keep learning

Follow a structured path or browse all courses to go deeper.