Q21: What is the purpose of the OAuth 2.0 `state` parameter and how does it prevent CSRF?

Difficulty:MediumTopic:OAuth Security

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:

  1. The client generates a random state value, saves it in user session storage, and appends it to the /authorize request URL.
  2. The Authorization Server returns the identical state string in the redirect callback URL alongside the authorization_code.
  3. The client compares the returned state parameter against the value stored in the user's session before requesting tokens.
  4. If an attacker attempts to force a victim to redeem a malicious authorization code, the state values will not match, blocking the request.
Key Takeaways
  • The state parameter binds authorization responses to the specific browser session that initiated them.
  • Always validate the returned state parameter string before exchanging authorization codes for tokens.