The Silent Session Hijack
Cross-Site Request Forgery (CSRF) is one of the most insidious attacks because it leverages the browser's own helpfulness. When you log in to your bank, the bank sets a session cookie. This cookie is automatically sent with every subsequent request to the bank's domain, even if that request originates from a different site.
Scenario: The Malicious Image
Imagine you are logged into your admin dashboard. You visit a forum, and someone posts an image: <img src='https://your-site.com/admin/delete-user?id=1' />. Your browser tries to load the image, inadvertently sending a GET request to your admin panel. Since your session cookie is attached, the request is authenticated, and the user is deleted.
Double Submit Cookie Pattern
To prevent this, modern frameworks like Laravel and Next.js use CSRF tokens. This involves generating a random string (token) on the server, storing it in the user's session, and requiring it to be present in every POST/PUT/DELETE request (usually as a hidden form field or header).
SameSite Cookie Attribute
The SameSite=Strict attribute is the modern browser's defense. It tells the browser: 'Do not send this cookie if the request comes from a different domain.' We verify why you should always set this flag for authentication cookies, while Lax might be acceptable for non-critical tracking cookies.
Conclusion
CSRF attacks are entirely preventable. By combining anti-CSRF tokens with strict cookie attributes, you close the door on session riding attacks.