For some odd reason, this only works when opensocial_token (and, I suppose, any part of the query string) does not have a space in it. When it does, authentication fails. What's wrong? How exactly should the code handle spaces? (rawurlencode() doesn't solve the problem either.)
(N.B. I cannot use Jerome's PHP Client Library as I have PHP 4 and the library is for PHP 5.)
$oauth_sec = xxxxxxxxxxxxxxxx'; // Secret
$remote_signature = $_GET['oauth_signature'];
$url = strtolower('http://' . $_SERVER['SERVER_NAME'] . reset(explode('?', $_SERVER['REQUEST_URI'])));
unset($_GET['oauth_signature']);
ksort($_GET);
$base_string = 'GET&' . urlencode($url) . '&' . urlencode(http_build_query($_GET));
$secret = $oauth_sec . '&';
$local_signature = base64_encode(hmac_sha1($secret, $base_string));
if ($remote_signature == $local_signature) {
echo 'Authenticated!';
} else {
echo 'Authentication failed!<br/>';
echo 'Remote Sig: ' . $remote_signature . '<br/>';
echo 'Local Sig: ' . $local_signature . '<br/>';
}
function hmac_sha1($key, $data) {
// hash_hmac() is only for PHP5; this is for backwards compatibility.
// From http://us.php.net/sha1 -- thanks Mark!
$blocksize = 64;
$hashfunc = 'sha1';
if (strlen($key) > $blocksize) $key = pack('H*', $hashfunc($key));
$key = str_pad($key, $blocksize, chr(0x00));
$ipad = str_repeat(chr(0x36), $blocksize);
$opad = str_repeat(chr(0x5c), $blocksize);
$hmac = pack('H*', $hashfunc(($key ^ $opad) . pack('H*', $hashfunc(($key ^ $ipad) . $data))));
return $hmac;
}