Symfony CSRF and Ajax

peterrus picture peterrus · Aug 21, 2012 · Viewed 21.2k times · Source

I am trying to implement some ajax functionality in my Symfony 2 project. Using jquery's $.post I want to send some data back to my controller. However, when I just POST the data no CSRF protection is in place, as symfony's csrf protection only seems to apply to forms.

What would be a pretty straightforward way to implement this?

When using forms I can just do $form->isValid() to find out whether or not the CSRF token passes. I am currently placing everything I want to POST in a form and then posting that. Which basically means I am only using that form to implement CSRF protection, which seems hacky.

Answer

Vitalii Zurian picture Vitalii Zurian · Aug 21, 2012

In Symfony2 CSRF token is based on session by default. If you want to generate it, you just have to get this service and call generation method:

//Symfony\Component\Form\Extension\Csrf\CsrfProvider\SessionCsrfProvider by default
$csrf = $this->get('form.csrf_provider');
//Intention should be empty string, if you did not define it in parameters
$token = $csrf->generateCsrfToken($intention); 

return new Response($token);

This question might be useful for you