Symfony-CSRF令牌无效-FosRestBundle [英] Symfony - CSRF token is invalid - FosRestBundle
问题描述
我正在使用Symfony和FosRestBundle。
I'm using Symfony and FosRestBundle.
当我只想测试我的其余api时,我得到了:
When I want to simply test my rest api, I got this :
CSRF令牌无效。请尝试重新提交表单。
The CSRF token is invalid. Please try to resubmit the form.
/**
* @example ["titre", "short description", "description", "2016-10-10", 200, "with complete data"]
* @example ["titre", "short description", "description", "2016-10-31", 200, "with complete data"]
*/
public function editNewsTest(ApiTester $I, Example $example)
{
$I->wantTo('edit a news (' . $example[5] . ')');
$I->haveHttpHeader('Content-Type', 'application/json');
$I->sendPUT('/news', ['title' => $example[0], 'shortDescription' => $example[1], 'description' => $example[2], 'date' => $example[3]]);
$I->seeResponseCodeIs($example[4]); // 200
$I->seeResponseIsJson();
}
此处是我的FosRestBundle配置:
Here my FosRestBundle configuration :
#FOSRestBundle
fos_rest:
service:
inflector: appbundle.util.inflector
param_fetcher_listener: force
body_listener:
array_normalizer: fos_rest.normalizer.camel_keys
format_listener: true
view:
view_response_listener: 'force'
formats:
json : true
templating_formats:
html: true
force_redirects:
html: true
failed_validation: HTTP_BAD_REQUEST
default_engine: twig
routing_loader:
default_format: json
include_format: false
serializer:
serialize_null: true
access_denied_listener:
json: true
exception:
enabled: true
messages:
Symfony\Component\HttpKernel\Exception\BadRequestHttpException: true
disable_csrf_role: IS_AUTHENTICATED_ANONYMOUSLY
推荐答案
如果您将请求数据验证为Symfony表单,那是正确的。使用 $ I-> sendPUT(...)
,您不会发送任何CSRF令牌,这就是为什么它会给您带来错误。
That's correct if you validate the request data as a Symfony Form. With $I->sendPUT(...)
you're not sending any CSRF token that's why it gives you the error.
您可以使用FOSRestBundle禁用CSRF的特定角色,请参见 http://symfony.com/doc/current/bundles/FOSRestBundle/2-the-view-layer.html#csrf-validation
You can disable CSRF with FOSRestBundle for specific roles, see http://symfony.com/doc/current/bundles/FOSRestBundle/2-the-view-layer.html#csrf-validation
另一种选择是当然也发送CSRF令牌。
The other option is to send also the CSRF token of course.
这篇关于Symfony-CSRF令牌无效-FosRestBundle的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!