-->

Symfony的 - CSRF令牌无效 - FosRestBundle(Symfony - CS

2019-09-28 21:47发布

我使用Symfony和FosRestBundle。

当我想简单的测试我的REST API,我得到这个:

该CSRF令牌无效。 请尝试重新提交表单。

/**
     * @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配置:

#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

Answer 1:

也就是说,如果您验证请求数据作为Symfony的形式是正确的。 随着$I->sendPUT(...)你不发送任何CSRF令牌,这就是为什么它给你的错误。

你可以用FOSRestBundle禁用CSRF特定角色,看到http://symfony.com/doc/current/bundles/FOSRestBundle/2-the-view-layer.html#csrf-validation

另一种选择是也派当然CSRF令牌。



Answer 2:

我没有经过认证,造成我security.yml看看这个:

dev:
    pattern: ^/
    security: false

我改变,并添加一个新的防火墙

dev:
    pattern: ^/(_(profiler|wdt)|css|images|js)/
    security: false

test:
    anonymous: ~
    pattern: ^/

现在有了这config.yml:

   disable_csrf_role: IS_AUTHENTICATED_ANONYMOUSLY

它的工作。

感谢马丁,帮助



文章来源: Symfony - CSRF token is invalid - FosRestBundle