gpt4 book ai didi

ajax - 在测试中获取CSRF token , "CSRF token is invalid"- 功能性ajax测试

转载 作者:行者123 更新时间:2023-12-04 18:07:19 25 4
gpt4 key购买 nike

我正在尝试测试 ajax Symfony2 中的请求。我正在编写一个单元测试,它在我的 app/logs/test.log 中抛出以下错误:

request.CRITICAL: Uncaught PHP Exception Twig_Error_Runtime: 
"Impossible to access an attribute ("0") on a string variable
("The CSRF token is invalid. Please try to resubmit the form.")
in .../vendor/twig/twig/lib/Twig/Template.php:388

我的代码相当简单。
public function testAjaxJsonResponse()
{
$form['post']['title'] = 'test title';
$form['post']['content'] = 'test content';
$form['post']['_token'] = $client->getContainer()->get('form.csrf_provider')->generateCsrfToken();

$client->request('POST', '/path/to/ajax/', $form, array(), array(
'HTTP_X-Requested-With' => 'XMLHttpRequest',
));

$response = $client->getResponse();
$this->assertSame(200, $client->getResponse()->getStatusCode());
$this->assertSame('application/json', $response->headers->get('Content-Type'));
}

问题似乎是 CSRF token ,我可以在测试中禁用它,但我真的不想这样做,我通过发出 2 个请求让它工作(第一个使用表单加载页面,我们获取 _token 并创建第二个request using with XMLHttpRequest ) - 这显然看起来相当愚蠢和低效!

最佳答案

解决方案

我们可以生成自己的 CSRF我们的 token ajax请求:

$client->getContainer()->get('form.csrf_provider')->generateCsrfToken($intention);

这里的变量 $intention指在您的 Form Type Options 中设置的数组键.

添加 intention
在您的 Form Type您需要添加 intention key 。例如:
# AcmeBundle\Form\Type\PostType.php

/**
* Additional fields (if you want to edit them), the values shown are the default
*
* 'csrf_protection' => true,
* 'csrf_field_name' => '_token', // This must match in your test
*
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Acme\AcmeBundle\Entity\Post',
// a unique key to help generate the secret token
'intention' => 'post_type',
));
}

Read the documentation

在您的功能测试中生成 CSRF token

现在我们有了 intention ,我们可以在我们的单元测试中使用它来生成一个有效的 CSRF token 。
/**
* Test Ajax JSON Response with CSRF Token
* Example uses a `post` entity
*
* The PHP code returns `return new JsonResponse(true, 200);`
*/
public function testAjaxJsonResponse()
{
// Form fields (make sure they pass validation!)
$form['post']['title'] = 'test title';
$form['post']['content'] = 'test content';

// Create our CSRF token - with $intention = `post_type`
$csrfToken = $client->getContainer()->get('form.csrf_provider')->generateCsrfToken('post_type');
$form['post']['_token'] = $csrfToken; // Add it to your `csrf_field_name`

// Simulate the ajax request
$client->request('POST', '/path/to/ajax/', $form, array(), array(
'HTTP_X-Requested-With' => 'XMLHttpRequest',
));

// Test we get a valid JSON response
$response = $client->getResponse();
$this->assertSame(200, $client->getResponse()->getStatusCode());
$this->assertSame('application/json', $response->headers->get('Content-Type'));

// Assert the content
$this->assertEquals('true', $response->getContent());
$this->assertNotEmpty($client->getResponse()->getContent());
}

关于ajax - 在测试中获取CSRF token , "CSRF token is invalid"- 功能性ajax测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24481042/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com