I’m having trouble working with my redirect uri in the authentication.
If i set it to my site, the user will authenticate, because $_Request['code'] is set, but then the user will be on my site, and I don’t want that
If I redirect to apps.facebook.com/myapp, then $_Request['code'] is not set, and the user won’t authenticate, but just see a blank page.
is there any way to do this in PHP, I have code running before the page is rendered.
How do you guys solve this issue?
my login function:
public static function login($redirect) {
$app_id = AppInfo::appID();
$app_secret = AppInfo::appSecret();
$home = urlencode(AppInfo::getHome());
// See https://developers.facebook.com/docs/reference/api/permissions/
// for a full list of permissions
$scope = 'user_photos,publish_stream';
session_start();
$code = $_REQUEST["code"];
// If we don't have a code returned from Facebook, the first step is to get
if (empty($code)) {
// CSRF protection - for more information, look at 'Security Considerations'
// at 'https://developers.facebook.com/docs/authentication/'
$state = md5(uniqid(rand(), TRUE));
setcookie(
AppInfo::appID() . '-fb-app',
$state,
$expires = 0,
$path = "",
$domain = "",
$secure = "",
$httponly = true);
// Now form the login URL that you will use to authorize your app
$authorize_url = "https://www.facebook.com/dialog/oauth?client_id=$app_id" .
"&redirect_uri=$home&state=" . $state . "&scope=$scope";
// Now we redirect the user to the login page
echo("<script> window.location.href='" . $authorize_url . "'</script>");
return false;
// Once we have that code, we can now request an access-token. We check to
// ensure that the state has remained the same.
} else if ($_REQUEST['state'] === $_COOKIE[AppInfo::appID() . '-fb-app']) {
$ch = curl_init("https://graph.facebook.com/oauth/access_token");
curl_setopt($ch, CURLOPT_POSTFIELDS,
"client_id=$app_id&redirect_uri=$home&client_secret=$app_secret" .
"&code=$code&scope=$scope");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
// Once we get a response, we then parse it to extract the access token
parse_str($response, $params);
$token = $params['access_token'];
return $token;
// In the event that the two states do not match, we return false to signify
// that something has gone wrong during authentication
} else {
echo("States do not match. CSRF?");
return false;
}
}
If you want to have your app on Facebook, you can just use the
signed_requestparameter Facebook POSTs to your canvas url. You wouldn’t need to read thecodeonce the user has approved your app. Note that Facebook always sends this parameter, even if the current user hasn’t approved your app (it contains less info then).See the documentation