Add OAuth Security with AI Prompts

TL;DR

OAuth is complex and easy to get wrong. Always use the state parameter, validate tokens server-side, use PKCE for public clients, and don't trust data from ID tokens without verification. These prompts help you implement OAuth without the common security holes.

Secure OAuth Flow Setup

Copy this prompt to implement an OAuth login flow with proper CSRF protection via the state parameter. Your AI will generate the full authorization redirect, state generation and session storage, callback verification, and replay-attack prevention.

AI Prompt

OAuth with State Parameter

Implement OAuth login with proper CSRF protection.

Provider: Google/GitHub/Discord Framework: Next.js/Express

Authorization request must include:

  1. state: cryptographically random value
  2. Store state in session before redirect
  3. Verify state matches on callback
  4. Use state only once

Implementation:

  1. Generate state: crypto.randomBytes(32).toString('hex')
  2. Store in session: session.oauthState = state
  3. Include in auth URL: &state={state}
  4. On callback: verify req.query.state === session.oauthState
  5. Delete state from session after verification

Reject callback if:

  • State is missing
  • State doesn't match session
  • State was already used

PKCE for Public Clients

Use this prompt to add PKCE (Proof Key for Code Exchange) to your OAuth flow. Your AI will generate code verifier and challenge creation, the modified authorization URL, and the token exchange logic that prevents authorization code interception.

AI Prompt

Add PKCE Protection

Implement PKCE (Proof Key for Code Exchange) for OAuth.

PKCE prevents authorization code interception attacks.

Flow:

  1. Generate code_verifier: random 43-128 character string
  2. Create code_challenge: base64url(sha256(code_verifier))
  3. Send code_challenge in authorization request
  4. Send code_verifier in token exchange

Implementation:

  • code_verifier = crypto.randomBytes(32).toString('base64url')
  • code_challenge = base64url(sha256(code_verifier))

Authorization URL: &code_challenge={challenge} &code_challenge_method=S256

Token request: code_verifier={verifier}

Store code_verifier in session alongside state. Both must be present and valid on callback.

Never skip the state parameter: Without state verification, attackers can use CSRF to log users into attacker-controlled accounts or steal authorization codes.

Token Handling

Paste this prompt to set up secure storage for OAuth access tokens, refresh tokens, and ID tokens. Your AI will generate encrypted storage patterns for server-side apps and Backend-for-Frontend (BFF) patterns for SPAs, keeping tokens out of the browser.

AI Prompt

Secure Token Storage

Handle OAuth tokens securely after authentication.

After token exchange, you receive:

  • access_token: for API calls
  • refresh_token: for getting new access tokens
  • id_token: user identity (if OpenID Connect)

Storage rules:

  1. Never expose tokens to client/frontend
  2. Store encrypted in database or secure session
  3. access_token: short-lived, can be in memory
  4. refresh_token: encrypt at rest, secure storage

For server-side apps:

  • Store tokens in encrypted session
  • Use httpOnly cookies for session ID
  • Refresh tokens before they expire

For SPAs (avoid if possible):

  • Use BFF (Backend for Frontend) pattern
  • Keep tokens server-side
  • Don't store tokens in localStorage

ID Token Verification

Copy this prompt to generate proper ID token verification logic. Your AI will create signature validation against the provider's JWKS, claim checks (issuer, audience, expiration), and safe extraction of user identity fields.

AI Prompt

Verify ID Tokens

Properly verify ID tokens from OAuth providers.

Never trust ID token claims without verification:

  1. Verify signature using provider's public keys
  2. Check iss (issuer) matches expected provider
  3. Check aud (audience) matches your client ID
  4. Check exp (expiration) is in the future
  5. Check iat (issued at) is reasonable
  6. For Google: check azp if multiple clients

Fetch provider's JWKS (JSON Web Key Set):

After verification:

  • Extract sub (subject) as stable user ID
  • email may not be verified - check email_verified claim
  • Don't trust name/picture without sanitizing

Use libraries: jose, jsonwebtoken with verify options

Pro tip: Use established OAuth libraries like NextAuth.js, Passport, or Auth.js instead of implementing OAuth yourself. They handle the security details correctly.

Should I use OAuth for my app?

OAuth (social login) is great for reducing friction and offloading password security. But you're trusting the provider, and users might not want to link accounts. Offer it alongside traditional login.

What's the difference between OAuth and OpenID Connect?

OAuth is for authorization (accessing resources). OpenID Connect adds authentication (identity) on top. When you need to know who the user is, you want OIDC which gives you an ID token.

Further Reading

Want to understand the vulnerability before fixing it? These guides explain what's happening and why.

Check Your OAuth Setup

Scan your OAuth implementation for security issues.

AI Fix Prompts

Add OAuth Security with AI Prompts