Created
October 7, 2009 07:24
-
-
Save ithinkihaveacat/203851 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function generate($consumer_key, $consumer_secret, $method, $url, $args) { | |
// http://oauth.net/core/1.0/#encoding_parameters | |
$encode = function($s) { | |
return str_replace("%7E", "~", rawurlencode($s)); | |
}; | |
// As described in section 9.1.3 of the spec, we need to take the hash of | |
// three strings: | |
// | |
// 1. The HTTP request method used to send the request. | |
// 2. The request URL | |
// 3. The normalized request parameters string | |
// | |
// See | |
// | |
// http://oauth.net/core/1.0/#rfc.section.9.1.3 | |
// 1. The HTTP request method used to send the request. | |
$method = strtoupper($method); | |
// 2. The request URL | |
$port = parse_url($url, PHP_URL_PORT); | |
if (is_null($port) || in_array($port, array(80, 443))) { | |
$port = ""; | |
} else { | |
$port = ":$port"; | |
} | |
$url = join( | |
"", | |
array( | |
strtolower(parse_url($url, PHP_URL_SCHEME)), | |
"://", | |
strtolower(parse_url($url, PHP_URL_HOST)), | |
$port, | |
strtolower(parse_url($url, PHP_URL_PATH)) | |
) | |
); | |
// 3. The normalized request parameters string | |
$base = array( | |
"oauth_consumer_key" => $consumer_key, | |
"oauth_signature_method" => "HMAC-SHA1", | |
"oauth_timestamp" => time(), | |
"oauth_nonce" => mt_rand(), | |
"oauth_version" => "1.0" | |
); | |
$args = array_merge($args, $base); // $args should not contain any keys matching oauth_*, especially oauth_signature | |
ksort($args, SORT_STRING); | |
$parameters = str_replace("%7E", "~", http_build_query($args)); | |
// Generate signature; see | |
// | |
// http://oauth.net/core/1.0/#rfc.section.9.2 | |
$text = join("&", array($encode($method), $encode($url), $encode($parameters))); | |
$key = join("&", array($encode($consumer_secret), "")); // Token secret is empty when doing two-legged OAuth | |
$signature = base64_encode(hash_hmac("sha1", $text, $key, true)); | |
$args["oauth_signature"] = $signature; | |
// Generate "Authorization" header; see | |
// | |
// http://oauth.net/core/1.0/#auth_header_authorization | |
$authorization = array(); | |
foreach ($args as $k => $v) { | |
$authorization[] = sprintf("%s=\"%s\"", $encode($k), $encode($v)); | |
} | |
return "OAuth " . join(", ", $authorization); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment