Disable CSRF token on login form

fkoessler picture fkoessler · Mar 7, 2013 · Viewed 23.2k times · Source

I am using Symfony2.0 and FOSUserBundle, and would like to disable the csrf token on my login form.

I have disabled the csrf protection globally on my website in my config.yml:

framework:
    csrf_protection:
        enabled:        false

This is working well, there is no csrf field added to my forms. However, this does not apply to the login form. On this form only, I get an "Invalid CSRF Token" error if I don't include the token in the form with:

<input type="hidden" name="_csrf_token" value="{{ csrf_token }}" />

How can I disable the CSRF token on the login form?

Answer

Juan Sosa picture Juan Sosa · Mar 7, 2013

You can disable CSRF protection in your form class by setting 'csrf_protection' => false in its options array:

class LoginType extends AbstractType
{
    // ...

    public function getDefaultOptions(array $options)
    {
        return array(
            'data_class'      => 'Acme\UserBundle\Entity\User',
            'csrf_protection' => false
        );
    }

    // ...

} 

In case you are using FormBuilder to create your form instead of an AbstractType class, you can pass the options array as the second parameter for createFormBuilder() like this:

$form = $this->createFormBuilder($users, array('csrf_protection' => false))
        ->add( ... )
        ->getForm();