我不理解"以下PHP示例在一个自包含的示例中演示了具有CSRF保护的服务器端流:"http://developers.facebook.com/docs/authentication/即为什么需要它?为什么session_start();是否需要?我不明白会话的工作从哪里开始或结束。CSRF保护是如何工作的?为什么用户登录后不立即返回访问令牌?
在脚本顶部调用session_start()
一次,然后再打印任何内容。
之后,您可以访问$_SESSION
阵列。这允许您在一个页面调用到另一个页面的调用中存储类似$_SESSION['state']
的值。
示例中的代码显示了CSRF保护。第一次调用tt时,会在会话中存储一个随机值,然后进行比较。
阅读有关php会话的更多信息。
更新带有注释的脚本。如果你看一下剧本上面的图片。。。我从那里"标记"了一些要点。
// Set your facebook config here
$app_id = "YOUR_APP_ID";
$app_secret = "YOUR_APP_SECRET";
$my_url = "YOUR_URL";
// start session to store random state
session_start();
// get a code from the request
$code = $_REQUEST["code"];
// if no code was send to the script...
if(empty($code)) {
// generate a random, unique id and store it the session
$_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
// create facebook dialog url
$dialog_url = "https://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
. $_SESSION['state'];
// redirect user to facebook
// Facebook login and App Permissions request
// "GET OAuth Dialog"
echo("<script> top.location.href='" . $dialog_url . "'</script>");
}
// CSRF protection: check if state parameter is the same as
// we stored it in the session before the redirect
if($_REQUEST['state'] == $_SESSION['state']) {
// do facebook auth "GET /oauth/authorize"
$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);
// "GET me?access_token"
$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.");
}