'11111111111', -6ren">
gpt4 book ai didi

php - Facebook SDK 返回错误 : Cross-site request forgery validation failed. URL 和 session 中的 "state"参数不匹配

转载 作者:IT老高 更新时间:2023-10-28 12:05:38 30 4
gpt4 key购买 nike

我正在尝试像这样使用 php sdk 获取 Facebook 用户 ID

$fb = new Facebook\Facebook([
'app_id' => '11111111111',
'app_secret' => '1111222211111112222',
'default_graph_version' => 'v2.4',
]);

$helper = $fb->getRedirectLoginHelper();


$permissions = ['public_profile','email']; // Optional permissions
$loginUrl = $helper->getLoginUrl('http://MyWebSite', $permissions);

echo '<a href="' . $loginUrl . '">Log in with Facebook!</a>';


try {
$accessToken = $helper->getAccessToken();
var_dump($accessToken);
} 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)) {
if ($helper->getError()) {
header('HTTP/1.0 401 Unauthorized');
echo "Error: " . $helper->getError() . "\n";
echo "Error Code: " . $helper->getErrorCode() . "\n";
echo "Error Reason: " . $helper->getErrorReason() . "\n";
echo "Error Description: " . $helper->getErrorDescription() . "\n";
} else {
header('HTTP/1.0 400 Bad Request');
echo 'Bad request';
}
exit;
}

// Logged in
echo '<h3>Access Token</h3>';
var_dump($accessToken->getValue());

// The OAuth 2.0 client handler helps us manage access tokens
$oAuth2Client = $fb->getOAuth2Client();

// Get the access token metadata from /debug_token
$tokenMetadata = $oAuth2Client->debugToken($accessToken);
echo '<h3>Metadata</h3>';
var_dump($tokenMetadata);

// Validation (these will throw FacebookSDKException's when they fail)
$tokenMetadata->validateAppId($config['11111111111']);
// If you know the user ID this access token belongs to, you can validate it here
//$tokenMetadata->validateUserId('123');
$tokenMetadata->validateExpiration();

if (!$accessToken->isLongLived()) {
// Exchanges a short-lived access token for a long-lived one
try {
$accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
} catch (Facebook\Exceptions\FacebookSDKException $e) {
echo "<p>Error getting long-lived access token: " . $helper->getMessage() . "</p>\n\n";
exit;
}

echo '<h3>Long-lived</h3>';
var_dump($accessToken->getValue());
}

$_SESSION['fb_access_token'] = (string)$accessToken;

但它给了我这个错误:

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

请提供任何帮助,我是 php 和 Facebook sdk 的新手,感谢您提前提供任何帮助。

最佳答案

我发现,只要我在生成登录 url 之前启用 PHP session ,并且在 Facebook 最终重定向到的脚本顶部,它就可以在不设置 cookie (as per ale500's answer) 的情况下自行工作。这里使用的是 5.1 版本的 sdk。

在两个脚本的顶部,我添加了...

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

...它“刚刚工作”。

这是一个对我有用的准系统完整示例:

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());
}

为什么?

作为附加说明,这在 repo 上的文档中进行了解释。查看 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.

我之所以添加此注释,是因为如果您碰巧在运行自己的 session 管理或并行运行多个 Web 服务器,请务必牢记这一点。在这些情况下,依赖 php 的默认 session 方法并不总是有效。

关于php - Facebook SDK 返回错误 : Cross-site request forgery validation failed. URL 和 session 中的 "state"参数不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32029116/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com