Disable symfony 2 csrf token protection on ajax submit

Julien Rollin picture Julien Rollin · Mar 27, 2012 · Viewed 56.5k times · Source

i'm building a mobile app talking to my symfony2 app via webservices I can't find a way to disable csrf protection on a specific controller/action

i want to post registration data to this action and use sf2 form validation. I do not call the form in my mobile app

Can't change container parameters in action, throw an exception because it is a frozen parameter...

I do not want to disable form protection for whole my application

any clue ?

thanks !

update: with symfony 2.1.x

/**
 * {@inheritdoc}
 */
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'csrf_protection'   => false,
    ));
}

Answer

Inoryy picture Inoryy · Mar 27, 2012

If you're looking for a bit easier and faster solution than suggested in answer above, here's how:

<?php

// ...

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\OptionsResolver\OptionsResolver;

class MyType extends AbstractType
{
    // ...

   public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'csrf_protection' => false,
        ));
    }
}

.. or if you're using older versions (Symfony 2.0.*):

<?php

// ...

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

class MyType extends AbstractType
{
    // ....

    public function getDefaultOptions(array $options)
    {
        $options = parent::getDefaultOptions($options);
        $options['csrf_protection'] = false;

        return $options;
    }
}

Consult the Symfony documentation for additional information.


Edit: updated answer to latest Symfony version, thanks naitsirch