1

我正在使用Symfony和FosRestBundle。Symfony - CSRF令牌無效 - 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 

回答

1

如果驗證請求數據作爲Symfony的形式是正確的。由於$I->sendPUT(...)你沒有發送任何CSRF令牌,這就是爲什麼它會給你帶來錯誤。

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

另一種選擇是也令牌的過程發送CSRF。

+0

嗨,我已經禁用了CSRF(disable_csrf_role:IS_AUTHENTICATED_ANONYMOUSLY) – Xero

+0

'IS_AUTHENTICATED_ANONYMOUSLY'不是一個角色。 http://stackoverflow.com/questions/39973519/symfony2-set-security-access-control-to-allow-only-authenticated-anonymously/39973846#39973846 – martin

+0

@Xero此處還描述了http://symfony.com/doc /current/security.html#checking-to-see-if-a-user-is-logged-in-is-authenticated -fully – martin

0

我沒有經過認證,造成我security.yml看看這個:

dev: 
    pattern: ^/ 
    security: false 

我改變這種狀況,並與這config.yml添加新的防火牆

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

test: 
    anonymous: ~ 
    pattern: ^/ 

現在:

disable_csrf_role: IS_AUTHENTICATED_ANONYMOUSLY 

它的工作。

感謝馬丁,幫助