功能测试中的Symfony 3.4和CSRF令牌

时间:2019-01-17 16:46:48

标签: symfony csrf

我正在使用Symfony 3.4进行一些功能测试,但是在提交带有CSRF令牌的表单时遇到问题。
我尝试了很多解决方案,但始终失败:

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')
    );
}

以我的形式:

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => Teacher::class,
        'csrf_token_id' => 'division_item',
    ));
}

我在做什么错了?

1 个答案:

答案 0 :(得分:2)

发生此问题是因为我在发出请求后 生成了CSRF令牌。这导致令牌生成了两次(我发现它将内容转储到CsrfTokenManager中。)

这有效:

// generates the CSRF token
$csrfToken = $client->getContainer()->get('security.csrf.token_manager')->getToken('division_item');

$crawler = $client->request('POST', '/teachers/add');