Facebook SDK returned an error: Cross-site request forgery validation failed. The “state” param from the URL and session do not match

后端 未结 25 1073
南方客
南方客 2020-12-01 01:37

i\'m trying to get Facebook user id using the php sdk like this

$fb = new Facebook\\Facebook([
    \'app_id\' => \'11111111111\',
    \'app_secret\' =>         


        
25条回答
  •  自闭症患者
    2020-12-01 02:11

    I got this error while using the Facebook SDK in Symfony2, writing a Twig Extension to display data from the API in templates.

    The solution for me was adding 'persistent_data_handler'=>'session' to the Facebook object config, which causes the state data to be stored in a session key instead of memory:

    $fb = new Facebook\Facebook([
        'app_id' => 'APP_ID',
        'app_secret' => 'APP_SECRET',
        'default_graph_version' => 'v2.4',
        'persistent_data_handler'=>'session'
    ]);
    

    By default, it was using the built-in memory handler, which didn't work properly for me. Maybe because some functions are being called from within a Twig Extension, as the memory handler does work when using the SDK exclusively in normal controllers/services.

    Apparently the state is set when you call getLoginUrl(), and is retrieved anytime you call getAccessToken(). If the saved state returns null (because your data handler isn't as persistent as it should be), the CSRF validation check fails.

    If you need to treat sessions in a particular way or you want to store the state somewhere else, you can also write your own handler with 'persistent_data_handler' => new MyPersistentDataHandler(), using the FacebookSessionPersistentDataHandler as an example.

提交回复
热议问题