【发布时间】:2012-01-22 19:34:58
【问题描述】:
我在身份验证中使用重定向 uri 时遇到问题。
如果我将其设置到我的站点,用户将进行身份验证,因为设置了$_Request['code'],但随后用户将在我的站点上,我不希望这样
如果我重定向到apps.facebook.com/myapp,则$_Request['code'] 未设置,用户不会进行身份验证,只会看到一个空白页面。
有没有办法在 PHP 中做到这一点,我在页面呈现之前运行了代码。
你们是怎么解决这个问题的?
我的登录功能:
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;
}
}
【问题讨论】:
-
@Jakob 我可以看到你的完整代码吗?你用那个代码是为了什么目的??
-
@mogulzalp 有没有办法在 php 中做到这一点,我在页面呈现之前运行了代码,这意味着用户的加载时间更少
-
我编辑了帖子 - 我希望这就是您的要求
-
@moguzalp - 好的。谢谢你的回答,这是我迄今为止最好的:)
-
@Jakob 我猜你应该添加这个代码 $post_login_url = "www.yoursite.com";尝试添加任何特定页面的网址,例如 www.yoursite.com/some-link
标签: php facebook facebook-apps