Created
April 30, 2013 13:44
-
-
Save deviantintegral/5488802 to your computer and use it in GitHub Desktop.
Example of simple 0-legged oauth request signing.
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
<?php | |
/** | |
* Sign a request to the Hackpad API using oauth 1.0. The Hackpad API doesn't | |
* use tokens or anything beyond a very basic oauth request. | |
* | |
* @params $uri | |
* The URI to make the request to. | |
* @param $method | |
* The HTTP method used for the request. | |
* @param $query | |
* An optional array of query parameters to add to the URI. | |
* | |
* @return | |
* An array of URL parameters suitable for appending to a request made to | |
* $uri. | |
*/ | |
protected function signRequest($uri, $method, $query = array()) { | |
$oauth = $query; | |
$oauth['oauth_consumer_key'] = $this->client_id; | |
$oauth['oauth_nonce'] = $this->nonce(); | |
$oauth['oauth_signature_method'] = 'HMAC-SHA1'; | |
$oauth['oauth_timestamp'] = time(); | |
$oauth['oauth_version'] = '1.0'; | |
// All parameters must be in alphabetical order for oauth hashing. | |
ksort($oauth); | |
// The most complicated part of the request - generating the signature. | |
// The string to sign contains the HTTP method, the URL we are loading, | |
// and all of our query parameters each URL encoded. Then, we concatenate | |
// them with ampersands into a single string to hash. | |
$http_verb = urlencode($method); | |
$resource_url = urlencode($uri); | |
// TODO: If you're not using Drupal, you'll need to change this call. | |
$url_parameters = urlencode(drupal_http_build_query($oauth)); | |
$sig_string = $http_verb . '&' . $resource_url . '&' . $url_parameters; | |
// Since we only have one oauth token (our shared secret) we only have to | |
// use it as our hmac key. However, we still have to append an & to it as | |
// if we were using it with additional tokens. | |
$secret = urlencode($this->secret) . '&'; | |
// This is a hash of the consumer key and the "base string". Note that we | |
// have to get the raw_output from hash_hmac but then base64 encode the | |
// binary data result. | |
$oauth['oauth_signature'] = base64_encode(hash_hmac('sha1', $sig_string, $secret, TRUE)); | |
return $oauth; | |
} | |
/** | |
* Generate a unique string for use with oauth requests. | |
* | |
* @return | |
* A unique string suitable to use with an oauth nonce parameter. | |
*/ | |
protected static function nonce() { | |
$mt = microtime(); | |
$rand = mt_rand(); | |
return md5($mt . $rand); // md5s look nicer than numbers | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment