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

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

    I found that as long as I enabled PHP sessions before generating the login url, and at the top of the script Facebook eventually redirects to, it works just fine on its own without setting a cookie (as per ale500's answer). This is using the 5.1 version of the sdk.

    At the top of both scripts, I added...

    if(!session_id()) {
        session_start();
    }
    

    ...and it "just worked".

    Here's a barebones complete example that worked for me:

    auth.php

    if (!session_id()) {
        session_start();
    }
    
    $oFB = new Facebook\Facebook([
        'app_id'     => FACEBOOK_APP_ID,
        'app_secret' => FACEBOOK_APP_SECRET
    ]);
    
    $oHelper = self::$oFB->getRedirectLoginHelper();
    $sURL = $oHelper->getLoginUrl(FACEBOOK_AUTH_CALLBACK, FACEBOOK_PERMISSIONS);
    
    // Redirect or show link to user.
    

    auth_callback.php

    if (!session_id()) {
        session_start();
    }
    
    $oFB = new Facebook\Facebook([
        'app_id'     => FACEBOOK_APP_ID,
        'app_secret' => FACEBOOK_APP_SECRET
    ]);
    
    $oHelper = self::$oFB->getRedirectLoginHelper();
    $oAccessToken = $oHelper->getAccessToken();
    if ($oAccessToken !== null) {
        $oResponse = self::$oFB->get('/me?fields=id,name,email', $oAccessToken);
        print_r($oResponse->getGraphUser());
    }
    

    Why?

    As an additional note, this is explained in the Docs on the repo. Look at the warning on this page.

    Warning: The FacebookRedirectLoginHelper makes use of sessions to store a CSRF value. You need to make sure you have sessions enabled before invoking the getLoginUrl() method. This is usually done automatically in most web frameworks, but if you're not using a web framework you can add session_start(); to the top of your login.php & login-callback.php scripts. You can overwrite the default session handling - see extensibility points below.

    I'm adding this note because it's important to keep in mind should you happen to be running your own session management or if you're running multiple web servers in parallel. In those cases, relying upon php's default session methods won't always work.

提交回复
热议问题