Cross site request forgery explained, and how Rails defends against it

TL;DR

Difficulty: Intermediate

Cross site request forgery (CSRF) borrows a logged in customer and makes their browser send a request to your shop they never meant to send.

  • The browser attaches the session cookie automatically, so a forged request looks exactly like something the customer did on purpose.
  • The payoff is account takeover, moved money or goods, quiet admin changes, or silent state changes that look legitimate in the logs.
  • AI brought the old attack back: Veracode found 2.74x more vulnerabilities in AI code, and the quickest way to clear a token error is to switch the protection off.
  • Rails defends with the authenticity token and protect_from_forgery, SameSite cookies, deliberate token auth for APIs, origin checks, and signed webhooks instead of a blanket skip.
  • I lock it in with Cucumber scenarios and Brakeman, and prove it from the outside with a pen test using Burp Suite and OWASP ZAP on Kali Linux.

Most attacks try to break into your server. Cross site request forgery does the opposite: it borrows a customer who is already logged in and quietly makes their browser act on your shop in their name. Here is what the attack is in plain words, a safe worked example of how it works, why AI assistants have made it likely again, and exactly how I defend against it in Rails and prove the defence holds.

The attack that uses your own customer against you

Most attacks on a web application try to break in from the outside. Cross site request forgery does the opposite. It never touches your server directly and it never steals a password. Instead it borrows a customer who is already logged in, and quietly makes their browser do something on your site that they never meant to do.

I build business critical web applications in Ruby on Rails, Solidus shops and smart websites, and I pen test every one of them before it goes live. Cross site request forgery, usually shortened to CSRF and often said out loud as "sea surf", is one of the oldest tricks on the web and still one of the easiest to get wrong, especially now that a lot of new code is written by an AI assistant that will happily switch the protection off to make a form work. This article explains what the attack is in plain words, shows you a safe worked example of how it works, and then walks through exactly how I defend against it in Rails and how I prove the defence holds.

What cross site request forgery actually is

Picture a customer, Nadia, who is logged in to your online shop in one browser tab. Her browser is holding a small file called a session cookie, which is how the shop knows that this tab belongs to Nadia and not a stranger. As long as that cookie is there, every request the browser sends to your shop is treated as coming from Nadia.

Now Nadia opens a second tab and lands on some unrelated page: a forum, a competition, an email with an image in it, anything at all. That page contains a hidden instruction that tells her browser to send a request to your shop. Here is the important part: when the browser sends that request, it automatically attaches Nadia's session cookie, because browsers attach the cookies for a site to every request bound for that site, no matter which page set the request going.

So your shop receives a request that carries Nadia's valid session, asks to change her delivery address or her email, and looks, from the server's point of view, exactly like something Nadia did on purpose. She did not. A page she had no reason to distrust spoke to your shop in her name. That is cross site request forgery: one site forging a request to another, riding on a login that already exists.

The key insight, and the thing that surprises people, is that the attacker never sees the cookie and never needs to. They do not read Nadia's session. They simply get her browser to use it. It is the difference between stealing someone's house key and getting them to open their own front door for you without realising it.

How the attack works, step by step

Let me make it concrete with a safe, illustrative example. It is deliberately not a working exploit against any real target, just enough to show the shape of the thing.

Imagine a shop that lets a logged in customer change the email address on their account by submitting a form. On the server, that form posts to a route like POST /account/email, and the controller reads a single field, the new address. A well built Rails app rejects any such request that does not also carry a secret token, but suppose a developer removed that check to get the feature working one afternoon and never put it back.

An attacker builds a page on their own site that contains a hidden form pointed straight at your shop:

<!-- attacker's own page, nothing to do with your shop -->
<form action="https://shop.example/account/email" method="POST" id="x">
  <input type="hidden" name="email" value="attacker@evil.example">
</form>
<script>document.getElementById("x").submit();</script>

When Nadia, still logged in, visits that page, the script submits the form the instant it loads. Her browser sends the POST to your shop and, as always, attaches her session cookie. Your shop sees a logged in request to change the account email, and with the token check gone, it obeys. Nadia's account email is now the attacker's email. A moment later the attacker clicks "forgot my password", the reset link arrives in their inbox, and the account is theirs.

Nadia saw nothing. There was no login box, no warning, no obvious redirect. The request happened in the background of a page she was simply reading. That silence is what makes the attack effective. Where cross site scripting runs the attacker's code on your page, cross site request forgery needs no code on your page at all. It only needs a logged in browser and one state changing request that trusts the cookie and nothing else.

It does not even always need a form. If a sensitive action is wired to a plain GET request, which it never should be, then an image tag is enough:

<img src="https://shop.example/account/delete?confirm=true" width="1" height="1">

The browser fetches that "image", sends the session cookie with it, and the account is gone. This is the oldest reason for the rule that a request which only reads data may use GET, but anything that changes data must use POST, PATCH, PUT or DELETE. It is not pedantry. It is the first line that keeps a casual link or a tracking pixel from quietly changing your customers' accounts.

What the attacker is really after

CSRF is rarely the goal in itself. It is a way in, and what sits behind it is the usual list: money, data and control.

Taking the account. The email change above is the classic path to a full account takeover. Once the attacker owns the recovery email, they own the account, the saved cards, the order history, the loyalty balance and the stored address book. In a shop that stores anything of value in an account, that is the whole prize.

Moving money or goods. On a site that can transfer funds, change payout details, redeem store credit or post an order to a new address, a single forged request can send money or stock to the attacker. Banking and payment flows are a favourite target for exactly this reason.

Quiet privilege. On an admin panel, a forged request might add a new administrator, change a price to zero, approve a refund or disable a security setting. The attacker does not need the admin's password. They need the admin to be logged in and to open one tab.

Changing state nobody checks. Even where there is no direct payout, a forged request can change a shipping address on a pending order, cancel a subscription, flip a setting, or post content in the victim's name. Each of these is a real incident for the business and the customer, and each is deniable, because from the logs it looks like the customer did it.

The real world consequence is not only the immediate loss. It is the support time, the chargebacks, the customer who no longer trusts you, and, where personal data was exposed, a reportable breach with regulators and a notification duty. A quiet attack has a loud aftermath.

Why AI has made this old attack likely again

CSRF was close to a solved problem. Mature frameworks turn the defence on by default, and for years a developer had to go out of their way to be vulnerable. What has changed is who, or what, is writing the code, and how well anyone understands it afterwards.

A great deal of new code is now produced by AI assistants, and the security evidence on that code is consistent and sobering. Veracode's 2025 GenAI Code Security Report found that AI generated code contains 2.74 times more vulnerabilities than code written by people. A 2025 analysis by Ox Security of more than 300 repositories found the same ten anti patterns in 80 to 100% of AI generated code, meaning these are not random slips but the same mistakes repeated at scale. Separate research found that 45% of AI generated code introduces a vulnerability from the OWASP Top 10, the standard list of the most common web application flaws. And a 2026 study of more than 304,000 commits found that 24.2% of the issues AI introduced survived unresolved, carried forward into the running product because nobody caught them. The Georgetown CSET report on the cybersecurity risks of AI generated code in 2024, and CrowdStrike's 2025 research into AI code vulnerabilities, point the same way.

Now apply that to CSRF specifically. The protection in a framework like Rails works because every form and every state changing request carries a secret token, and the server refuses any request that lacks it. That is also precisely the thing that gets in the way when you are wiring up a new endpoint in a hurry. When a form, an API call or a webhook returns a token error, the quickest way to make the red go away is to switch the check off. An AI assistant asked to "make this POST work" will readily suggest exactly that: add skip_forgery_protection to the controller, or disable the token for this action, and the error disappears along with the defence. The code runs, the demo works, and nobody reviewing it realises that the guard on every logged in action has just been removed. This is the pattern behind that 24.2% figure: a plausible fix that passes the eye test and quietly reopens an old hole.

The deeper problem is understanding. When code is generated rather than written, and shipped without tests, there is often nobody on the team who can say why the token check was removed, whether it was scoped to one safe endpoint or left off everywhere, or what a given controller actually trusts. CSRF thrives in exactly that gap, because it exploits trust that the code grants silently.

How I defend against it in Rails

Ruby on Rails has strong, built in protection against CSRF, and most of my job is to keep it on, use it correctly, and prove it works. Here is what that means in practice.

The authenticity token

Rails defends with a secret value called the authenticity token. When the server renders a form, it embeds a token that only your application knows how to produce and verify, tied to the user's session. When the form is submitted, Rails checks that the token is present and valid before the controller runs. A forged request coming from an attacker's page cannot include a valid token, because the attacker cannot read it from your pages, so the request is rejected before it does any harm.

In a modern Rails application this is switched on in the base controller with one line:

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
end

with: :exception means a request with a missing or wrong token is refused outright rather than silently stripped of its session. The Rails view helpers add the token to every form automatically, so for ordinary forms there is nothing extra to write. The discipline is simply never to switch it off globally, and never to use a state changing GET, so that the token actually covers the actions that matter.

SameSite cookies, the second lock

The authenticity token is the main defence. Modern browsers give me a second, independent one: the SameSite attribute on the session cookie. It tells the browser when it is allowed to attach the cookie to a request that was started by another site. With SameSite=Lax, the browser withholds the session cookie from most cross site requests, including the hidden form POST in the example above, while still allowing a normal top level navigation when someone clicks a genuine link to your shop. Rails sets a sensible SameSite default on its session cookie, and I confirm it on every build rather than assuming it:

Rails.application.config.session_store :cookie_store,
  key: "_shop_session",
  same_site: :lax,
  secure: Rails.env.production?

secure: true in production means the cookie only ever travels over an encrypted connection. SameSite and the token are belt and braces: the token stops a forged request that somehow carries the cookie, and SameSite stops the cookie travelling with the forged request in the first place. I use both, because each covers edge cases the other does not.

Why APIs use token authentication instead

CSRF is fundamentally a flaw of cookie based sessions, because cookies ride along automatically. An API that does not use cookies is not vulnerable in the same way. So for the parts of a system that are APIs, a single page front end talking to a JSON backend, or a mobile app, I authenticate with a token that the client holds and sends deliberately in an Authorization header, rather than a cookie the browser sends for free. Because a malicious page cannot read that token and cannot make the browser attach it, there is nothing to forge. This is why Rails lets you treat API controllers differently: they do not rely on the session cookie, so the CSRF token is not the right tool there, and bearer token authentication is. The rule I follow is simple. If authentication rides on a cookie, the CSRF token must be on. If it rides on a deliberate header, it need not be, and the endpoint must refuse cookie authentication so nobody can downgrade it.

Verifying the origin

As a further check on sensitive actions, the server can look at where the request claims to have come from. Browsers attach Origin and Referer headers that name the page that started the request. On a genuine submission these name your own site. On a forged one they name the attacker's. Checking that the origin of a state changing request matches your own host is a cheap, strong extra signal, and it is especially useful on the highest value actions such as changing payout details or admin settings. I treat it as defence in depth, never as the only defence, because headers can be absent in rare clients, but as an added gate it closes doors.

The honest exceptions, handled honestly

There is one place the token legitimately cannot apply: incoming webhooks from a payment provider such as the one that confirms a Solidus order has been paid. The provider's server is not a browser, has no token, and must be allowed to post to a specific endpoint. The wrong fix is to switch forgery protection off for the whole controller. The right fix is to skip the token for that one webhook action only, and replace it with a stronger check that suits a server to server call: verify the cryptographic signature the provider sends with every webhook. That way the endpoint trusts the request because it is signed by the provider, not because it carries a session it never should. The difference between a secure shop and a vulnerable one is often exactly this: the exception is scoped to one action and backed by a signature, rather than a blanket skip_forgery_protection that quietly covers everything.

Locking the defence in with tests

Turning the protection on is not enough. I have to be able to prove, now and after every future change, that it is still on and still covers the actions that matter. That is what automated tests are for, and it is where behaviour driven tests earn their place.

I write scenarios in Cucumber, which lets me describe behaviour in plain English that a business owner can read, and then runs that description as a real test against the application. A CSRF scenario reads like a sentence of policy:

Feature: Account email is protected against forged requests

  Scenario: a request without a valid token is refused
    Given I am signed in as a customer
    When a request to change my email arrives without a valid authenticity token
    Then the request is rejected
    And my account email is unchanged

That scenario fails loudly the moment someone adds a careless skip_forgery_protection, removes the token check, or wires a sensitive action to a GET. It turns an invisible security property into a visible, checkable promise. I keep one of these for every state changing action that matters, so the protection cannot be quietly undone by a later change, whether a person or an AI assistant makes it. Alongside the behaviour scenarios I run Brakeman, the static analysis tool for Rails, on every build. Brakeman reads the code without running it and flags exactly this kind of mistake, including forgery protection that has been switched off, so the warning lands in the pull request rather than in production.

Pen testing: proving it from the outside

Tests check the application from the inside, against the behaviour I expect. Penetration testing checks it from the outside, the way an attacker would, against behaviour I did not expect. Before a build goes live I probe it with the standard tools on Kali Linux, the Linux distribution built for security testing.

For CSRF the workhorse is an intercepting proxy such as Burp Suite or OWASP ZAP, which sits between a browser and the application and shows every request. With it I can take a genuine request, strip out the authenticity token, replay it, and confirm the server refuses it. I can generate a proof of concept forged request and check that SameSite and the token both stop it. I can walk every state changing endpoint and confirm none of them has been left unprotected, including the admin and the webhook paths. ZAP and Burp both have CSRF specific checks that flag forms without a token and cookies without a SameSite attribute, so the review is systematic rather than a matter of remembering every route. The point of doing this with the attacker's own tools is that I am testing the running system, not my assumptions about it.

Why this is insurable, verifiable work

The thread running through all of the above is that I do not treat the application as a black box. I own readable code, I understand what every controller trusts, every state changing path has a test that locks its protection in, and every release is probed from the outside before it reaches a customer. That is the difference between hoping an app is secure and being able to show that it is.

It matters commercially, not just technically. When the protection against forged requests is written down as a scenario a business owner can read, checked by Brakeman on every build, and confirmed by a pen test before release, you have evidence. You can show an insurer, an auditor or a worried customer the test that holds the line and the report that confirms it. A vibe coded app where nobody can say whether the token check is on, or where it was removed, has no such evidence, and that absence is exactly what both attackers and underwriters notice. Verifiable security is the kind you can stand behind.

In closing

Cross site request forgery is an old attack that quietly came back, because the easiest way to clear a token error is to remove the token, and a lot of today's code is written by tools that will suggest doing exactly that. The defence in Rails is solid and mostly built in: keep the authenticity token on, set SameSite on the session cookie, use deliberate token authentication for APIs, verify the origin on the actions that matter, and handle the genuine exceptions like webhooks with a signature rather than a blanket switch off. Then lock all of it in with behaviour tests and confirm it with a pen test, so the protection cannot be undone without someone noticing.

If you are not sure whether your shop or application is protected, or whether a token check was switched off somewhere to make a feature work, that is worth knowing rather than guessing. I run a free workshop where we look at your real risks together and I show you where you stand, with no obligation and the first two weeks of any work on me. You are welcome to bring the awkward questions.

If you are not sure whether your shop is protected, or whether a token check was switched off to make a feature work, book the free workshop: we look at your real risks together, and the first two weeks of any work are on me.

Shelter

I’m running the London Marathon for Shelter. Sunday 25 April 2027

My personal fundraiser. Shelter, the National Campaign for Homeless People Limited, registered charity 263710 (England and Wales) and SC002327 (Scotland), registered with the Fundraising Regulator.