通过加密的 cookie 信息对 facebook 用户进行身份验证的方法很好:
这里的代码:
// PHP script which get visitor's FB ID over $_GET['fbid'] (for example through ajax or javascript redirect)
if(isset($_GET['fbid'])) {
define('FACEBOOK_APP_ID', 'YOUR APP ID');
define('FACEBOOK_SECRET', 'YOUR SECRET ID');
function parse_signed_request($signed_request, $secret) {
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
// decode the data
$sig = base64_url_decode($encoded_sig);
$data = json_decode(base64_url_decode($payload), true);
if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
error_log('Unknown algorithm. Expected HMAC-SHA256');
return null;
}
// check sig
$expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
if ($sig !== $expected_sig) {
error_log('Bad Signed JSON signature!');
return null;
}
return $data;
}
function base64_url_decode($input) {
return base64_decode(strtr($input, '-_', '+/'));
}
// Check if Facebooks cookie is set
if(isset($_COOKIE['fbsr_' . FACEBOOK_APP_ID])) {
$response = parse_signed_request($_COOKIE['fbsr_' . FACEBOOK_APP_ID], FACEBOOK_SECRET);
// Check if userID sent by visitor is the same like decrypted userID given from cookie
if($response['user_id'] == $_GET['fbid']) {
// Login script here
echo "Successfully authenticated!";
} else {
// userID sent by visitor is modified
echo "Please don't use others FB ID!";
}
} else {
// Facebook cookie is not set
echo "Please allow cookies!";
}
}