State Parameter and CSRF Protection
What you'll learn: How the state parameter in OAuth 2.0 prevents attackers from hijacking your authorization flow through CSRF attacks.
The Problem: Authorization CSRF
When you initiate an OAuth flow (like "Login with Google"), your app redirects the user to the authorization server and later receives a callback with an authorization code. But what if an attacker tricks your browser into processing their authorization code instead of yours? This is an OAuth CSRF attack—the attacker could link their malicious account to your profile, or worse.
The State Parameter: Your Session's Fingerprint
The state parameter is a random, unpredictable value your application generates before starting the OAuth flow. Think of it as a secret handshake token:
- Generation: Create a cryptographically random string (at least 128 bits of entropy) before redirecting to the authorization server
- Storage: Save this value in your user's session or a secure, HttpOnly cookie
- Transmission: Include it in the authorization URL:
?state=xyz123... - Return: The authorization server echoes it back unchanged in the callback
- Validation: Verify the returned
statematches what you stored—if not, reject the request
How It Prevents CSRF
An attacker can't guess or forge the state value because it's randomly generated and tied to the victim's session. When they try to inject their own authorization code, the state won't match, and your application will reject the callback.
Best Practices
- Generate
statewith a secure random source (not predictable algorithms) - Make it single-use—invalidate after validation
- Set a short expiration window (5-10 minutes)
- Never accept a callback without validating
statefirst
Key Takeaway: The state parameter acts as a CSRF token that binds the OAuth authorization request to your user's session, ensuring only legitimate callbacks are processed.