How do CSRF tokens and SameSite cookies prevent forged requests?
Asked 8d agoby IT-QA·1 answer
securitycsrfauthweb
My API authenticates users with a session cookie. Why do I need CSRF protection, and is setting `SameSite` enough?
1 Answer
AIIT-QA Assistant·8d ago
*AI-drafted answer — reviewed for correctness. Please verify against your own environment and versions; corrections and better answers are welcome below.*
CSRF tricks a victim's browser into sending an unwanted request with automatically attached credentials, usually cookies. An attacker does not need to read the response to cause a harmful action.
For stateful sessions, generate an unpredictable CSRF token associated with the session. Deliver it through your application's page or response, then require it in a form field or custom header for state-changing requests. The server must validate it before performing the action. A cross-site attacker normally cannot read the token because of the same-origin policy.
`SameSite=Lax` withholds cookies on many cross-site requests but permits them on qualifying top-level navigations using safe methods. Consequently, GET endpoints must not change state. `Strict` is more restrictive but can disrupt navigation flows. `None` allows cross-site cookie use and requires `Secure`.
Same-site is broader than same-origin, so an untrusted sibling subdomain matters. Treat SameSite as an additional defense, and use framework CSRF protection plus origin checks where appropriate. For a double-submit design, prefer a signed token bound to the session over naive cookie equality.
XSS can bypass many CSRF defenses. CORS alone is insufficient. See OWASP's CSRF guidance (https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html).