Q21: What is the purpose of the OAuth 2.0 `state` parameter and how does it prevent CSRF?
The state parameter is an opaque, unguessable cryptographic token generated by the client application before initiating an authorization code redirect.
How it prevents CSRF in OAuth:
- The client generates a random state value, saves it in user session storage, and appends it to the
/authorizerequest URL. - The Authorization Server returns the identical
statestring in the redirect callback URL alongside theauthorization_code. - The client compares the returned
stateparameter against the value stored in the user's session before requesting tokens. - If an attacker attempts to force a victim to redeem a malicious authorization code, the
statevalues will not match, blocking the request.
Key Takeaways
- The
stateparameter binds authorization responses to the specific browser session that initiated them. - Always validate the returned
stateparameter string before exchanging authorization codes for tokens.