Reputation: 2895
I am doing some functional tests with Symfony 3.4 but I have a problem submitting a form with a CSRF token.
I tried a lot of solutions but it keeps failing:
private function makeAuthenticatedClient()
{
$credentials = array(
'username' => $this->user->getUsername(),
'password' => $this->user->getPassword(),
);
return $this->makeClient($credentials);
}
public function testAdd()
{
$client = $this->makeAuthenticatedClient();
$crawler = $client->request('POST', '/teachers/add');
// generates the CSRF token
$csrfToken = $client->getContainer()->get('security.csrf.token_manager')->getToken('division_item');
$client->request(
'POST',
'/teachers/add',
[
'teachers' => [
'name' => 'Test',
'_token' => $csrfToken,
]
],
[],
['HTTP_X-Requested-With' => 'XMLHttpRequest']
);
$this->assertTrue(
$client->getResponse()->isRedirect('/teachers/list')
);
}
And in my form:
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => Teacher::class,
'csrf_token_id' => 'division_item',
));
}
What am I doing wrong?
Upvotes: 5
Views: 2786
Reputation: 2895
The problem occurred because I was generating the CSRF token after making the request. This caused the token to be generated twice (I discovered it dumping things in CsrfTokenManager
).
This works:
// generates the CSRF token
$csrfToken = $client->getContainer()->get('security.csrf.token_manager')->getToken('division_item');
$crawler = $client->request('POST', '/teachers/add');
Upvotes: 11