Deactivating CSRF for individual instances of Symfony forms

If you are creating an API controller in Symfony, you obviously cannot rely on the CSRF (Cross Site Request Forgery) token because the form is generated outside of your website and submitted to your website from an external source. Symfony defaults to CSRF protection on, so you will need to deactivate CSRF protection or data will not process and you will receive a “CSRF Token is Invalid” or other CSRF error.

public function getDefaultOptions(array $options){
       return array(
           'data_class'      => 'Acme\TaskBundle\Entity\Task',
           'csrf_protection' => false,  // <---- set this to false on a per Form Type basis
           //'csrf_field_name' => '_token',

$form = $this->createFormBuilder($formVals, array(
    'csrf_protection' => false,  // <---- set this to false on a per Form Instance basis

Be careful, however, because this is a point of vulnerability for your system if you no longer lock your forms down using CSRF. It is recommended to isolate access and take other precautions, like request source validation or locking requests down by IP or specific domain through your .htaccess and/or programmatically to avoid any cross site request attacks.

About Author:

Senior Cloud Software Engineer and 25+ years experienced video production, video editing and 3D animation services for a variety of global clients including local video production here in Jacksonville, Florida.

Leave a Comment

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