我正在尝试测试我的创建操作。它只是获取json内容传递的数据(应用程序使用backbonejs)并再次验证相应的表单类型。表单仍然指示错误“csrf令牌无效”。测试环境使用MockFileSessionStorage生成csrf标记。我尝试生成令牌,然后将会话cookie与请求一起发送,但它没有用。
贝娄是测试班。
<?php
namespace Company\ServiceBundle\Tests\Controller;
use Liip\FunctionalTestBundle\Test\WebTestCase;
use Symfony\Bundle\FrameworkBundle\Client;
use Symfony\Component\BrowserKit\Cookie;
use Symfony\Component\Form\Extension\Csrf\CsrfProvider\CsrfProviderInterface;
class EntidadeControllerTest extends WebTestCase
{
public function testCreate()
{
$dados = array(
'nome' => 'Entidade TESTE 01',
'ativo' => 0,
'_token' => $this->csrfDefaultToken
);
$crawler = $this->client->request(
'POST',
'/admin/entidades',
array(),
array(),
array(
'CONTENT_TYPE' => 'application/json',
'HTTP_X-Requested-With' => 'XMLHttpRequest'
),
json_encode(array('cartorio_servico_entidade'=>$dados))
);
$this->assertEquals(201, $this->client->getResponse()->getStatusCode());
}
/** @var Client $client */
protected $client;
/** @var CsrfProviderInterface $csrfProvider */
protected $csrfProvider;
/** @var string $csrfDefaultToken */
protected $csrfDefaultToken;
protected function setUp()
{
$this->csrfProvider = $this->getContainer()->get('form.csrf_provider');
$this->csrfDefaultToken = $this->csrfProvider->generateCsrfToken('unknown');
$this->client = static::createClient(
array(),
array('PHP_AUTH_USER' => 'admin', 'PHP_AUTH_PW' => '123456')
);
// session cookie - necessario para nao dar problema com o CSRF token
$cookie = new Cookie('PHPSESSID', $this->getContainer()->get('session')->getId(), time() + 3600 * 24 * 7, '/', null, false, false);
$this->client->getCookieJar()->set($cookie);
$fixtures = array(
'Company\ServiceBundle\DataFixtures\ORM\LoadUserData'
);
$this->loadFixtures($fixtures);
}
}
Bellow是动作代码。这真的只是一个简单的验证表单数据并继续。
/**
* Create new resource or just display the form.
*
* @param Request $request
*
* @return Response
*/
public function createAction(Request $request)
{
$config = $this->getConfiguration();
$resource = $this->createNew();
$form = $this->getForm($resource);
if ($request->isMethod('POST') && $form->bind($request)->isValid()) {
/** @var ResourceEvent $event */
$event = $this->create($resource);
if (!$event->isStopped()) {
return new Response(json_encode('criado'), 201, array('Content-Type' => 'application/json'));
}
}
if ($config->isApiRequest()) {
return $this->handleView($this->view($form));
}
return new Response(json_encode('nao criado'), 404, array('Content-Type' => 'application/json'));
}
答案 0 :(得分:0)
一种入门方法是将其添加到表单类型类中:
// TODO: remove this once we have auth working.
$resolver->setDefaults(array(
'csrf_protection' => false,
));
显然需要考虑安全性,但这可能有助于新手的发展。