Symfony Published on

Protecting a delete action with a CSRF token

A "Remove" link sent as a GET deletes the dish for the first bot that comes along: switch to POST, with a CSRF token for each dish.

Topics covered: SecurityCSRFTwig

On this restaurant's menu, each dish has its "Remove" link. A link is a GET request. And a GET goes out without anyone asking for it: a browser prefetching the links of the page, a bot crawling the site, an extension. Any other site can also trigger one with a simple image:

<img src="https://restaurant.example/dish/cassoulet/remove" alt="">

The logged-in manager's browser loads the image with its cookies, and the cassoulet disappears from the menu. This is a CSRF attack (Cross-Site Request Forgery): the attacker steals nothing, they make the victim's browser act.

Two protections

An action that changes data goes through POST. A route limited to POST answers a GET with a 405: no more prefetching or booby-trapped images. But another site can still make the browser post a hidden form to your URL.

The CSRF token makes the difference. It is a random value tied to the session, placed in the form. The other site cannot read it, so it cannot send it back. In Twig, csrf_token('an-identifier') generates it. In the controller, which receives the Request as an argument, isCsrfTokenValid() checks it, with the same identifier:

if (!$this->isCsrfTokenValid('remove-dish-'.$id, $request->request->getString('_token'))) {
    throw new AccessDeniedHttpException('Invalid CSRF token.');
}

One identifier per dish ('remove-dish-'.$id) gives one token per dish: the token of one row cannot empty another. It is also the most common trap: an identifier that differs between the template and the controller, and every submission is rejected.

The #[IsCsrfTokenValid('remove-dish')] attribute does the same check before the controller is called. For an identifier that depends on the dish, it needs an Expression from the ExpressionLanguage component. Here, we stick to isCsrfTokenValid(): the check reads in the controller, without depending on ExpressionLanguage.

To do

Replace each "Remove" link with a "Remove" button, in a form sent with POST and a CSRF token specific to the dish. The menu_remove route only accepts POST, and rejects a request whose token is missing or belongs to another dish.

To go further: the article The CSRF token across frameworks explains when the token is still needed in the age of SameSite cookies.