Course contentsShow
← Web Development
Lesson 1622 of 2,98229. Web Authentication PatternsFree lesson

State Parameter for CSRF Protection

Using the state parameter to prevent CSRF attacks during OAuth flows and validate callbacks.

State Parameter for CSRF Protection

You'll learn how the state parameter acts as a secret handshake to prevent attackers from hijacking OAuth callbacks.

The CSRF Problem in OAuth

When you redirect users to an OAuth provider (like "Sign in with Google"), they'll eventually return to your callback URL with an authorization code. But here's the danger: an attacker could trick your app into accepting their authorization code, potentially logging you into their account or stealing your credentials.

This Cross-Site Request Forgery (CSRF) attack happens because your callback endpoint can't tell if you initiated the OAuth flow or if an attacker forced a malicious redirect.

How the State Parameter Protects You

The state parameter is a random, unguessable string you generate before redirecting to the OAuth provider:

  1. Generate a cryptographically random string (like "f83a9d6b2c1e")
  2. Store it in the user's session (server-side) or encrypted cookie
  3. Send it in the authorization URL: https://provider.com/oauth?client_id=...&state=f83a9d6b2c1e
  4. Provider echoes it back unchanged in the callback
  5. Verify the returned state matches what you stored

Analogy: It's like giving someone a unique ticket stub before they leave, then checking they return with the matching stub. Without it, you don't know if this person actually belongs to your session.

// Before redirect
const state = crypto.randomBytes(32).toString('hex');
req.session.oauthState = state;

// In callback handler
if (req.query.state !== req.session.oauthState) {
  throw new Error('CSRF detected: state mismatch');
}

Key Takeaway: Always use the state parameter in OAuth flows—it's your only defense against CSRF attacks on authorization callbacks, ensuring the person who started the login is the same person completing it.