5

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?

1 Answer 1

11

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');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.