OAuth2 State Parameter is a random, unguessable value that the client generates and includes in the authorization request. It's returned unchanged in the callback, allowing the client to verify the response corresponds to its original request—preventing CSRF attacks.
// 1. Client generates random state and stores in session
state = generate_random_string()
session['oauth_state'] = state
// 2. Include state in authorization request
GET /authorize?
response_type=code&
client_id=app123&
state=abc123xyz& // <-- state parameter
redirect_uri=...
// 3. Auth server returns state in callback
GET /callback?code=AUTH_CODE&state=abc123xyz
// 4. Client verifies state matches session
if params['state'] != session['oauth_state']:
raise CSRFError("State mismatch")
// Attack: Attacker initiates OAuth, gets callback URL
// Attacker: https://victim-app.com/callback?code=ATTACKER_CODE
// Attacker tricks victim into visiting this URL
// Victim's account now linked to attacker's OAuth account!