Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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')
);
like image 409
bux Avatar asked Mar 01 '12 21:03

bux


1 Answers

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' => '[email protected]',
            '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.

like image 75
Karol Kasprzak Avatar answered Sep 19 '22 18:09

Karol Kasprzak