当Facebook通过$ _GET发送code
,state
参数时,它看起来像身份验证位,不在PHP-SDK中。
if(!empty($_GET['code']) && !empty($_GET['state']))
{
$response = file_get_contents('https://graph.facebook.com/oauth/access_token?' . http_build_query(array('client_id' => AY_FACEBOOK_APP_ID, 'client_secret' => AY_FACEBOOK_APP_SECRET, 'redirect_uri' => AY_FACEBOOK_TAB_URL, 'code' => $_GET['code'])));
// now check state and parse access token
ay($response);
}
我忽视了什么吗?如果没有,那么不包括它的原因是什么?
请注意,我没有要求提供一个例子,就像DMCS和Luc Franken到目前为止所做的那样。
答案 0 :(得分:2)
是的,有关CSRF保护的部分中http://developers.facebook.com/docs/authentication/讨论了状态和代码参数。
<?php
$app_id = "YOUR_APP_ID";
$app_secret = "YOUR_APP_SECRET";
$my_url = "YOUR_URL";
session_start();
$code = $_REQUEST["code"];
if(empty($code)) {
$_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
. $_SESSION['state'];
echo("<script> top.location.href='" . $dialog_url . "'</script>");
}
if($_REQUEST['state'] == $_SESSION['state']) {
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret . "&code=" . $code;
$response = @file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$graph_url = "https://graph.facebook.com/me?access_token="
. $params['access_token'];
$user = json_decode(file_get_contents($graph_url));
echo("Hello " . $user->name);
}
else {
echo("The state does not match. You may be a victim of CSRF.");
}
?>
答案 1 :(得分:-1)
$response = file_get_contents(
'https://graph.facebook.com/oauth/access_token?' . http_build_query(
array(
'client_id' => AY_FACEBOOK_APP_ID,
'client_secret' => AY_FACEBOOK_APP_SECRET,
'redirect_uri' => AY_FACEBOOK_TAB_URL,
'code' => $_GET['code']
)
)
);
// now check state and parse access token
ay($response);
那读起来好一点。
现在你的问题:它的确有效: https://graph.facebook.com/oauth/access_token?client_id=1&client_secret=2&redirect_uri=3&code=1234
使用此测试代码:
echo 'https://graph.facebook.com/oauth/access_token?' . http_build_query(
array(
'client_id' => 1,
'client_secret' => 2,
'redirect_uri' => 3,
'code' => '1234'
)
);
尝试将url放在变量中,这样可以在调试时更轻松。
如果你没有在code = part中得到任何东西,你可能在$ _GET ['code']变量中有值,而http_build_query将不会接受该值,因为该函数会对数组数据进行urlen编码。