Reputation: 602
I don't understand the code that comes after "The following PHP example demonstrates the server-side flow with CSRF protection in one self-contained example:" at http://developers.facebook.com/docs/authentication/ i.e Why is it needed? Why session_start(); is needed? I don't understand where the work with the session begins or ends. How does the CSRF protection work? Why access token is not returned right after user login?
Upvotes: 0
Views: 733
Reputation: 23542
You call session_start()
once at the top of your script, before anything it printed out.
After that you have access to the $_SESSION
array. This allows you to store values like $_SESSION['state']
from one page call to another.
The code in the example shows a CSRF protection. The first time you call tt stores a random value in the session and compares it afterwards.
Read more about php sessions.
Update Script with comments. If you have a look at the picture above the script... I "marked" some points from there.
// 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.");
}
Upvotes: 1