I did a very simple PHP script, just to try to login via Facebook and get an accessToken. But when I try the following code, I get an Exception from the SDK : « Cross-site request forgery validation failed. Required param "state" missing. ».
Here is my code :
require_once __DIR__ . '/facebook-sdk-v5/autoload.php';
session_start();
$fb = new Facebook\Facebook([
'app_id' => '{my-own-app-id}',
'app_secret' => '{my-own-app-secret}'
]);
// Check to see if we already have an accessToken ?
if (isset($_SESSION['facebook_access_token'] )) {
$accessToken = $_SESSION['facebook_access_token'];
echo "Horray we have our accessToken:$accessToken<br />\n";
} else {
// We don't have the accessToken
// But are we in the process of getting it ?
if (isset($_REQUEST['code'])) {
$helper = $fb->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (isset($accessToken)) {
// Logged in!
$_SESSION['facebook_access_token'] = (string) $accessToken;
// Now you can redirect to another page and use the
// access token from $_SESSION['facebook_access_token']
echo "Finally logged in! Token:$accessToken";
}
} else {
// Well looks like we are a fresh dude, login to Facebook!
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email', 'user_likes']; // optional
$loginUrl = $helper->getLoginUrl('http://mywebsite.com/myapp/index.php', $permissions);
echo '<a href="' . $loginUrl . '">Log in with Facebook!</a>';
}
}
exit;
The fix for me was to change
'secure' => true
tofalse
in config/session.php. I had accidently set this to true while not using https in the first place.To those of you of you who use cakephp 3.x and have this problem and you have no clue how to solve it. Add session_start(); at the beginning of your auth and callback method.
For me the problem is solved now just by starting the session by adding this:
at the beginning of both files (the first file generating facebook url and the callback file: login.php and fb-callback.php (https://developers.facebook.com/docs/php/howto/example_facebook_login)).
I also had to add this:
at the top of to prevent another non related error.
you have to make sure that the session start before the script runs. but again it will throw an
443: Network is unreachable
if you start a session again on the same script. hope this helps some one.I just used
if (session_status() == PHP_SESSION_NONE){ session_start(); }