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

后端 未结 25 1058
南方客
南方客 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:30

    The Facebook object has an instance variable called persistentDataHandler, usually an instance of FacebookSessionPersistentDataHandler, which has a set and a get method to access the native PHP sessions.

    When generating the callback url using:

    $loginUrl = $helper->getLoginUrl($callback_url, $permissions);
    

    The methode FacebookRedirectLoginHelper->getLoginUrl() will create a 32-character random string, add it to the $loginUrl and save it to the code below using the persistentDataHandler's set method.

    $_SESSION['FBRLH_' . 'state']
    

    Later when the $helper->getAccessToken(); is called, the state param in the url will be compared to the stored in the same session to prevent CSRF. If not match, this will exception be thrown.

    FacebookSDKException: Cross-site request forgery validation failed. Required param "state" missing.

    All these being said, you need to make sure your native PHP session feature is properly set during this process. You can check it, by adding

    die($_SESSION['FBRLH_' . 'state']);
    

    after

    $loginUrl = $helper->getLoginUrl($callback_url, $permissions);
    

    and before

    $accessToken = $helper->getAccessToken();
    

    to see if that 32-character string is there.

    Hope it helps!

提交回复
热议问题