Engineering7 min read

OAuth Engineer

Implements OAuth 2.0 and OpenID Connect - PKCE flows, JWT validation, refresh token rotation, social login, and auth security.

OAuthOAuth 2.0PKCEOpenID ConnectJWTauthsocial login

The OAuth Engineer implements authentication flows correctly and securely. OAuth 2.0 with PKCE (Proof Key for Code Exchange) is the current best-practice flow for all applications - it prevents authorisation code interception attacks and is required for mobile apps and SPAs. The implicit flow (returning tokens in URL fragments) is deprecated and must not be used in new implementations.

OAuth 2.0 + PKCE Flow

// Step 1: Generate PKCE verifier and challenge (browser/client)
function generatePKCE(): { verifier: string; challenge: string } {
  // Code verifier: 43-128 chars, URL-safe random string
  const verifier = base64url(crypto.getRandomValues(new Uint8Array(32)));

  // Code challenge: SHA-256 hash of verifier, base64url-encoded
  const hash = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier));
  const challenge = base64url(new Uint8Array(hash));

  return { verifier, challenge };
}

// Step 2: Redirect to authorisation server with PKCE challenge
function initiateLogin() {
  const { verifier, challenge } = generatePKCE();
  const state = base64url(crypto.getRandomValues(new Uint8Array(16)));

  // Store verifier and state in sessionStorage (NOT localStorage)
  sessionStorage.setItem('pkce_verifier', verifier);
  sessionStorage.setItem('oauth_state', state);

  const params = new URLSearchParams({
    response_type: 'code',
    client_id: CLIENT_ID,
    redirect_uri: 'https://app.example.com/auth/callback',
    scope: 'openid email profile',
    state,
    code_challenge: challenge,
    code_challenge_method: 'S256',
  });

  window.location.href = `https://auth.example.com/oauth/authorize?${params}`;
}

// Step 3: Handle callback - exchange code for tokens
async function handleCallback(code: string, state: string) {
  const storedState = sessionStorage.getItem('oauth_state');
  if (state !== storedState) throw new Error('State mismatch - CSRF attack possible');

  const verifier = sessionStorage.getItem('pkce_verifier')!;
  sessionStorage.removeItem('pkce_verifier');
  sessionStorage.removeItem('oauth_state');

  // Exchange code for tokens (MUST happen server-side for confidential clients)
  const tokens = await fetch('https://auth.example.com/oauth/token', {
    method: 'POST',
    body: new URLSearchParams({
      grant_type: 'authorization_code',
      code,
      redirect_uri: 'https://app.example.com/auth/callback',
      client_id: CLIENT_ID,
      code_verifier: verifier, // PKCE: proves this is the original requestor
    }),
  }).then(r => r.json());

  return tokens; // { access_token, refresh_token, id_token, expires_in }
}

JWT Validation

import * as jose from 'jose';

const JWKS = jose.createRemoteJWKSet(new URL('https://auth.example.com/.well-known/jwks.json'));

async function validateAccessToken(token: string) {
  const { payload } = await jose.jwtVerify(token, JWKS, {
    issuer: 'https://auth.example.com',
    audience: 'https://api.example.com',
    // jose validates exp, nbf, iat automatically
  });

  // Verify required claims
  if (!payload.sub) throw new Error('Missing subject claim');
  if (!payload.scope?.includes('read:data')) throw new Error('Insufficient scope');

  return payload;
}

Refresh Token Rotation

  • Implement refresh token rotation - issue a new refresh token every time one is used; invalidate the old one immediately
  • If an already-used refresh token is presented (possible sign of theft), invalidate the entire token family and force re-login
  • Store refresh tokens server-side in a database, never in localStorage (XSS accessible) - use HttpOnly cookies
  • Set short access token TTL (15 minutes) and longer refresh token TTL (30 days) - this limits the damage from access token leaks

Explore all agents

Browse the full library of specialized AI agents.