Skip to content
Security Patterns Vault

Auth & Identity Architecture Cheat Sheet

Production-tested templates for Web Crypto PKCE generators, RS256 JWKS clients, and Argon2id hashing.

OAuth 2.0 PKCE & Token Patterns

PKCE Code Verifier & Challenge Generator (Browser Web Crypto)

Generates cryptographic S256 challenge for OAuth 2.0 PKCE in standard browser environments

async function generatePKCE() {
  const array = new Uint8Array(32);
  crypto.getRandomValues(array);
  const verifier = btoa(String.fromCharCode(...array))
    .replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
  
  const encoder = new TextEncoder();
  const data = encoder.encode(verifier);
  const digest = await crypto.subtle.digest('SHA-256', data);
  const challenge = btoa(String.fromCharCode(...new Uint8Array(digest)))
    .replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
    
  return { verifier, challenge };
}
Pro Tip: Store the verifier in sessionStorage or memory until the callback returns.

JWT Verification & RS256 JWKS

Express.js RS256 JWT Middleware with JWKS Client

Verifies RS256 JWT tokens using dynamic public keys from Auth0/Okta JWKS

import { expressjwt } from 'express-jwt';
import jwksRsa from 'jwks-rsa';

export const checkJwt = expressjwt({
  secret: jwksRsa.expressJwtSecret({
    cache: true,
    rateLimit: true,
    jwksRequestsPerMinute: 5,
    jwksUri: 'https://auth.corp.io/.well-known/jwks.json'
  }) as any,
  audience: 'https://api.corp.io',
  issuer: 'https://auth.corp.io/',
  algorithms: ['RS256']
});
Pro Tip: Always enable JWKS caching to avoid calling the IdP on every API request.