Implement Slim / csrf with twig

Hello and thank you for your help

my problem is in the rendering of the token in the template twig
when i display the getEnvironment ()
the token are well generated
but impossible to access the values.

39

![21|241x30]34

after submission

message : Failed CSRF check!

source

thank you very much

I also ran into this issue, just a side note if you set session security to samesite as strict csrf is not really needed.

Anyway I created a twig function that generates this input for me so all I do it {{ csrf() }} and done.

To get to the problem are you sure that hidden output matches any of the values in the array?

Reason I’m asking is that every time a new http request was made a new key pair would be generated so your key might not be in the session array yet?

Within my twig function I would just use the last entry in the session data instead of calling the generate function on the guard class.

<?php


namespace App\Helpers\TwigExtension;



use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

class CsrfTwigExtension extends AbstractExtension
{

    public function getFunctions()
    {
        return [
            new TwigFunction('csrf', [$this, 'csrfTwig']),
        ];
    }

    public function csrfTwig()
    {

        $lastKey = array_key_last($_SESSION['csrf']);
        $lastValue = $_SESSION['csrf'][$lastKey];

        return "
            <input type='hidden' name='csrf_name' value='". $lastKey ."'>
            <input type='hidden' name='csrf_value' value='". $lastValue ."'>
        ";
    }


}

From the docs:

By default, Slim\Csrf\Guard will generate a fresh name/value pair after each request. This is an important security measure for certain situations. However, in many cases this is unnecessary, and a single token throughout the user’s session will suffice. By using per-session requests it becomes easier, for example, to process AJAX requests without having to retrieve a new CSRF token (by reloading the page or making a separate request) after each request. See issue #49.`

Just enable the persitent token mode to keep the token:

$guard->setPersistentTokenMode(true);

Hello and thank you

it is true that I asked myself the question of whether it was useful to implement session security with the csrf.
https://scotthelme.co.uk/csrf-is-really-dead/
and your function is sexy. my problem was that my tpl did not return the keys
thank you for your advice

Thanks :stuck_out_tongue: like I said just try getting the values from the session and you should be good to go. good luck…