phpsymfonytestingcsrf

Get the CSRF token in test


I'm writing functional test and i need to make ajax post request. "The CSRF token is invalid. Please try to resubmit the form". How can i get the token in my functional test ?

$crawler = $this->client->request(
  'POST', 
  $url, 
  array(
      'element_add' => array(
          '_token' => '????',
          'name'   => 'bla',
      )

  ), 
  array(), 
  array('HTTP_X-Requested-With' => 'XMLHttpRequest')
);

Solution

  • CSRF token generator is normal symfony 2 service. You can get service and generate token yourself. For example:

        $csrfToken = $client->getContainer()->get('form.csrf_provider')->generateCsrfToken('registration');
        $crawler = $client->request('POST', '/ajax/register', array(
            'fos_user_registration_form' => array(
                '_token' => $csrfToken,
                'username' => 'samplelogin',
                'email' => 'sample@fake.pl',
                'plainPassword' => array(
                    'first' => 'somepass',
                    'second' => 'somepass',
                ),
                'name' => 'sampleuser',
                'type' => 'DSWP',
            ),
        ));
    

    The generateCsrfToken gets one important parameter intention which should be the same in the test and in the form otherwise it fails.