我正在尝试使用Facebook身份验证登录我的网站,它运行正常。然而,当我使用https://apps.facebook.com/myApp访问应用程序时,我得到了一个错误
状态不匹配。您可能是CSRF的受害者
以下是我在facebook上使用的代码,我认为
存在问题$ my_url
<?php
$app_id = "YOUR_APP_ID";
$app_secret = "YOUR_APP_SECRET";
$my_url = "https://www.example.com/login.php";
session_start();
$code = $_REQUEST["code"];
if(empty($code)) {
$_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
$dialog_url = "https://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.");
}
?>
答案 0 :(得分:0)
你真的应该看看facebook为FTP提供的SDK。然后您不需要重新创建任何图形调用,因为它们都是为您处理的。
但有两个问题:
您需要在登录调用中编码整个返回URL,即
&amp; redirect_uri =“。urlencode($ my_url。”&amp; state =“。$ _SESSION ['state']);
如果要将数据传递到iFrame,则需要在名为“app_data”的参数中发送 - 所有其他参数都将被删除。此app_data将在“已签名的请求”中发送,因此您需要解码signed_request。详细信息http://developers.facebook.com/docs/authentication/signed_request/(再次使用facebook SDK,因为它可以轻松处理签名请求!)。