Search code examples
symfonytwigcsrf

Symfony: make CSRF token available to all twig templates


My app has AJAX requests here and there, and I want to protect them with CSRF tokens. However, rather than generating and passing a CSRF token to the Twig renderer for use in the JavaScript, I'd like a CSRF token to be readily available in every html page that Twig renders.

I've seen that Laravel seems to put it in a meta tag, so I can easily grab it with JavaScript. But how to do this in Symfony? How can I insert this token in every page?

Or is this not good practice?


Solution

  • Of course this is a good practice!!

    You have the built-in function csrf_token('key') in symfony/twig for that.

    Example:

    <a href="{{ path('product_remove', {id: product.id, csrf: csrf_token('product') }) }}" 
       class="btn btn-info">Remove</a>
    

    From a controller, you just have to check it:

    /**
     * @Route("/product/remove/{csrf}/{id}", name="product_remove")
     */
    public function removeProductAction($csrf, $id)
    {
        if ($csrf !== $this->get('security.csrf.token_manager')->getToken('product')->getValue()) {
            throw new InvalidCsrfTokenException('Invalid CSRF token');
        }
    
        // delete $id
    
        // cleans up url
        return $this->redirectToRoute('product_list');
    }
    

    all the things