CSRF and request integrity
Why request intent matters
Cross-site request forgery (CSRF) concerns a browser sending an unwanted state-changing request with a user’s existing credentials. A valid session establishes who is signed in, not whether the person intended this particular action. A bookstore must check both authorization and request integrity before changing a delivery address.
Use framework CSRF protection
For a stateful web application, a synchronizer token is an unpredictable value associated with the session and checked by the server on protected requests. Use the framework’s maintained protection rather than inventing token generation or comparison. Include the token in the intended form field or approved request header, not the URL; keep it out of logs. Reject missing or invalid tokens without changing state.
Add independent layers
Use safe HTTP methods such as GET for read-only operations; a POST alone does not establish intent. Apply a suitable SameSite cookie policy, validate the request Origin against trusted origins where appropriate, and use framework CSRF checks. Define how to handle missing origin information and legitimate cross-site integrations. Sensitive operations can additionally require reauthentication or explicit confirmation.
Avoid false guarantees
CORS may prevent a script from reading a response but does not universally prevent a request from reaching the server. HttpOnly limits cookie reading but is not a CSRF defense by itself. SameSite helps reduce cross-site cookie sending but is not a substitute for robust CSRF protection. Script injection in a trusted page can undermine request-integrity controls; retain output encoding and CSP.
Practice: decide before writing
In a fictional bookstore, approve an address update only if the session is active, the user owns the record, the method is POST, the framework reports a valid CSRF token and the origin is permitted by the lab policy. If any check fails, leave the record unchanged. These are boolean teaching inputs, not an actual token validator or an HTTP server.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
CSRF and request integrity — knowledge check
Reason about browser and server controls using fictional cases.
What does CSRF protection help establish?
Where should a synchronizer token not appear?
Which design is appropriate for a GET catalog request?
A valid session submits an update with an invalid CSRF token. What should happen?
Why combine SameSite with framework CSRF protection?