CSRF protection

the cross-site request forgery, abbreviated CSRF. The object of this attack is to transmit to an authenticated user a falsified HTTP request that points to an action internal to the site, so that he executes it without being aware of it and using his own rights. The user therefore becomes an accomplice to an attack without even realizing it. Since the attack is user-driven, a large number of authentication systems are bypassed.


  • Suppose that Alice is the administrator of a forum and that she is connected to it by a system of sessions. Malorie is a member of this same forum, she wants to delete one of the forum posts. As she does not have the necessary rights with her account, she uses Alice's account thanks to a CSRF type attack.
  • Malorie manages to know the link that allows you to delete the message in question. Malorie sends a message to Alice containing a pseudo-image to display (which is actually a script). The image URL is the link to the script to delete the desired message.
  • Alice must have an open session in her browser for the site targeted by Malorie. This is a requirement for the attack to succeed silently without requiring an authentication request that would alert Alice. This session must have the required rights to execute Malorie's destructive request. There is no need for a browser tab to be open on the target site or even for the browser to be started. It is enough that the session is active.
  • Alice reads Malorie's message, her browser uses Alice's open session and does not require interactive authentication. It attempts to retrieve the contents of the image. By doing this, the browser activates the link and deletes the message, it retrieves a text web page as content for the image. Not recognizing the type of image associated, it does not display an image and Alice does not know that Malorie has just made him delete a message against his will.

The strategy is simple, just add a secret key in the form (only known by the site and not by the attacker) and check the accuracy of this key upon receipt of the form.

form side first action

To add a key and store it in the session, a twig function exists to generate the necessary hidden input, then just prevent twig from neutralizing it with the raw filter, like that:

{{ getToken()|raw }}

Post side next actions

Now that a key has been added to the form, you must check that this key exists and that it is valid.

If is is valid, then we can process the form, if not, we must ... do something else.

to check if token is valid, there is a validator function, just like that:

$tokenValid = $this->checkToken($_POST['token'] ?? "");
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $tokenValid)

To complete this documentation there is always the example of the "item CRUD" provided by default in the mini-framework