Skip to content

Instantly share code, notes, and snippets.

@maligree
Created April 23, 2013 14:51
Show Gist options
  • Save maligree/5444207 to your computer and use it in GitHub Desktop.
Save maligree/5444207 to your computer and use it in GitHub Desktop.
A down-to-earth reference implementation of the wicked OAuth signing process. Without a token secret.
<?php
/*
* No-frills OAuth 1.0 request signing code.
* For reference see:
* https://dev.twitter.com/docs/auth/creating-signature
*/
function get_sig($uri, $c_key, $c_secret) {
$method = 'GET';
$raw_params = array(
'oauth_version' => '1.0',
'oauth_timestamp' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_nonce' => md5(microtime().mt_rand()),
'oauth_consumer_key' => $c_key
);
$enc_params = array();
/* percent encode parameters and values */
foreach ($raw_params as $k => $v) {
$enc_params[urlencode($k)] = urlencode($v);
}
/* sort alphabetically */
ksort($enc_params);
/* join them as required, with = and & */
$param_string = '';
foreach ($enc_params as $k => $v) {
$param_string .= $k;
$param_string .= '=';
$param_string .= $v;
$param_string .= '&';
}
/* fix trailing ampersand */
$param_string = rtrim($param_string, '&');
/* build final base string */
$base_string = '';
$base_string .= strtoupper($method);
$base_string .= '&';
$base_string .= urlencode($uri);
$base_string .= '&';
$base_string .= urlencode($param_string);
/* build key, we're not using a token secret in our case */
$key = urlencode($c_secret) . '&';
/* passing true to hash_hmac makes it return binary data */
return base64_encode(hash_hmac('sha1', $base_string, $key, true));
}
/* Example: */
print get_sig('https://api.example.com/api/oauth/some/resource', 'alamakota', 'alamakota');
print "\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment