We know that, the right way to change persistent data in database is only using POST (or PUT) requests, but in real life in each application we have many places that can change, add or remove data in database via GET request and you need to protect these actions.

  • Subscribe/Unsubscribe
  • Activation of users after registration (via security url)
  • Trivial operations with objects in datagrids (especially when transforming object from one state to another)
  • Setting custom filters in complex search forms.
  • Etc

To protect your application from CSRF you can create Type for each action (e.g. activation, subscription), but this is too long, tedious and also goes against RAD.

On the other hand, you can every time get form.csrf_provider from service container then validate this token manually.

To automate this routine https://github.com/korotovsky/csrf-validator-bundle was written.

After installation of this bundle, you should just add a special annotation to action that you want to protect.

Annotation @Krtv\Csrf has 2 parameters:

  • param – allows you to change name of the CSRF-token
  • intention – sets intention, that will be attached to this token

That’s it. Validation will be invoked during kernel.controller event.

4 comments on “Automatic CSRF-token validation in Symfony2

  • In twig template you can simple use it:
    {{ path('important_zone_route', { token: csrf_token('your_intention') }) }}

    • I’m using the Template PHP in place of Twig. Coud you tell how can i use it ?
      Using csrf_token function go trought an exception error
      > Attempted to call function “csrf_token

      I tried call csrfToken but it doesn’t work too.

      Thnks in advance.

      • Hi Gilson,

        You should try to find a way how to register your own service into $view variable. csrf_token() function in twig is just a facade to security.csrf.token_manager service.

  • Thanks for sharing this!

    I just added some CSRF token checking to a controller and thought I’d create an annotation to slim the actions down a bit. Turns out you beat me to it by two years! :)

Leave a Reply

Your email address will not be published. Required fields are marked *