├── http_socket_oauth.php └── readme.markdown /http_socket_oauth.php: -------------------------------------------------------------------------------- 1 | 24 | * @link http://www.neilcrookes.com 25 | * @copyright (c) 2010 Neil Crookes 26 | * @license MIT License - http://www.opensource.org/licenses/mit-license.php 27 | */ 28 | class HttpSocketOauth extends HttpSocket { 29 | 30 | /** 31 | * Default OAuth parameters. These get merged into the $request['auth'] param. 32 | * 33 | * @var array 34 | */ 35 | var $defaults = array( 36 | 'oauth_version' => '1.0', 37 | 'oauth_signature_method' => 'HMAC-SHA1', 38 | ); 39 | 40 | /** 41 | * Overrides HttpSocket::request() to handle cases where 42 | * $request['auth']['method'] is 'OAuth'. 43 | * 44 | * @param array $request As required by HttpSocket::request(). NOTE ONLY 45 | * THE ARRAY TYPE OF REQUEST IS SUPPORTED 46 | * @return array 47 | */ 48 | function request($request = array()) { 49 | 50 | // If the request does not need OAuth Authorization header, let the parent 51 | // deal with it. 52 | if (!isset($request['auth']['method']) || $request['auth']['method'] != 'OAuth') { 53 | return parent::request($request); 54 | } 55 | 56 | // Generate the OAuth Authorization Header content for this request from the 57 | // request data and add it into the request's Authorization Header. Note, we 58 | // don't just add the header directly in the request variable and return the 59 | // whole thing from the authorizationHeader() method because in some cases 60 | // we may not want the authorization header content in the request's 61 | // authorization header, for example, OAuth Echo as used by Twitpic and 62 | // Twitter includes an Authorization Header as required by twitter's verify 63 | // credentials API in the X-Verify-Credentials-Authorization header. 64 | $request['header']['Authorization'] = $this->authorizationHeader($request); 65 | 66 | // Now the Authorization header is built, fire the request off to the parent 67 | // HttpSocket class request method that we intercepted earlier. 68 | return parent::request($request); 69 | 70 | } 71 | 72 | /** 73 | * Returns the OAuth Authorization Header string for a given request array. 74 | * 75 | * This method is called by request but can also be called directly, which is 76 | * useful if you need to get the OAuth Authorization Header string, such as 77 | * when integrating with a service that uses OAuth Echo (Authorization 78 | * Delegation) e.g. Twitpic. In this case you send a normal unauthenticated 79 | * request to the service e.g. Twitpic along with 2 extra headers: 80 | * - X-Auth-Service-Provider - effectively, this is the realm that identity 81 | * delegation should be sent to - in the case of Twitter, just set this to 82 | * https://api.twitter.com/1/account/verify_credentials.json; 83 | * - X-Verify-Credentials-Authorization - Consumer should create all the OAuth 84 | * parameters necessary so it could call 85 | * https://api.twitter.com/1/account/verify_credentials.json using OAuth in 86 | * the HTTP header (e.g. it should look like OAuth oauth_consumer_key="...", 87 | * oauth_token="...", oauth_signature_method="...", oauth_signature="...", 88 | * oauth_timestamp="...", oauth_nonce="...", oauth_version="...". 89 | * 90 | * @param array $request As required by HttpSocket::request(). NOTE ONLY 91 | * THE ARRAY TYPE OF REQUEST IS SUPPORTED 92 | * @return String 93 | */ 94 | function authorizationHeader($request) { 95 | 96 | $request['auth'] = array_merge($this->defaults, $request['auth']); 97 | 98 | // Nonce, or number used once is used to distinguish between different 99 | // requests to the OAuth provider 100 | if (!isset($request['auth']['oauth_nonce'])) { 101 | $request['auth']['oauth_nonce'] = md5(uniqid(rand(), true)); 102 | } 103 | 104 | if (!isset($request['auth']['oauth_timestamp'])) { 105 | $request['auth']['oauth_timestamp'] = time(); 106 | } 107 | 108 | // Now starts the process of signing the request. The signature is a hash of 109 | // a signature base string with the secret keys. The signature base string 110 | // is made up of the request http verb, the request uri and the request 111 | // params, and the secret keys are the consumer secret (for your 112 | // application) and the access token secret generated for the user by the 113 | // provider, e.g. twitter, when the user authorizes your app to access their 114 | // details. 115 | 116 | // Building the request uri, note we don't include the query string or 117 | // fragment. Standard ports must not be included but non standard ones must. 118 | $uriFormat = '%scheme://%host'; 119 | if (isset($request['uri']['port']) && !in_array($request['uri']['port'], array(80, 443))) { 120 | $uriFormat .= ':' . $request['uri']['port']; 121 | } 122 | $uriFormat .= '/%path'; 123 | if (strpos(Configure::version(), "1.2") === 0) { 124 | $requestUrl = $this->buildUri($request['uri'], $uriFormat); 125 | } else { 126 | $requestUrl = $this->_buildUri($request['uri'], $uriFormat); 127 | } 128 | 129 | // OAuth reference states that the request params, i.e. oauth_ params, body 130 | // params and query string params need to be normalised, i.e. combined in a 131 | // single string, separated by '&' in the format name=value. But they also 132 | // need to be sorted by key, then by value. You can't just merge the auth, 133 | // body and query arrays together then do a ksort because there may be 134 | // parameters with the same name. Instead we've got to get them into an 135 | // array of array('name' => '', 'value' => '') elements, then 136 | // sort those elements. 137 | 138 | // Let's start with the auth params - however, we shouldn't include the auth 139 | // method (OAuth), and OAuth reference says not to include the realm or the 140 | // consumer or token secrets 141 | $requestParams = $this->assocToNumericNameValue(array_diff_key( 142 | $request['auth'], 143 | array_flip(array('realm', 'method', 'oauth_consumer_secret', 'oauth_token_secret')) 144 | )); 145 | 146 | // Next add the body params if there are any and the content type header is 147 | // not set, or it's application/x-www-form-urlencoded 148 | if (isset($request['body']) && (!isset($request['header']['Content-Type']) || stristr($request['header']['Content-Type'], 'application/x-www-form-urlencoded'))) { 149 | $requestParams = array_merge($requestParams, $this->assocToNumericNameValue($request['body'])); 150 | } 151 | 152 | // Finally the query params 153 | if (isset($request['uri']['query'])) { 154 | $requestParams = array_merge($requestParams, $this->assocToNumericNameValue($request['uri']['query'])); 155 | } 156 | 157 | // Now we can sort them by name then value 158 | usort($requestParams, array($this, 'sortByNameThenByValue')); 159 | 160 | // Now we concatenate them together in name=value pairs separated by & 161 | $normalisedRequestParams = ''; 162 | foreach ($requestParams as $k => $requestParam) { 163 | if ($k) { 164 | $normalisedRequestParams .= '&'; 165 | } 166 | $normalisedRequestParams .= $requestParam['name'] . '=' . $this->parameterEncode($requestParam['value']); 167 | } 168 | 169 | // The signature base string consists of the request method (uppercased) and 170 | // concatenated with the request URL and normalised request parameters 171 | // string, both encoded, and separated by & 172 | $signatureBaseString = strtoupper($request['method']) . '&' 173 | . $this->parameterEncode($requestUrl) . '&' 174 | . $this->parameterEncode($normalisedRequestParams); 175 | 176 | // The signature base string is hashed with a key which is the consumer 177 | // secret (assigned to your application by the provider) and the token 178 | // secret (also known as the access token secret, if you've got it yet), 179 | // both encoded and separated by an & 180 | $key = ''; 181 | if (isset($request['auth']['oauth_consumer_secret'])) { 182 | $key .= $this->parameterEncode($request['auth']['oauth_consumer_secret']); 183 | } 184 | $key .= '&'; 185 | if (isset($request['auth']['oauth_token_secret'])) { 186 | $key .= $this->parameterEncode($request['auth']['oauth_token_secret']); 187 | } 188 | 189 | // Finally construct the signature according to the value of the 190 | // oauth_signature_method auth param in the request array. 191 | switch ($request['auth']['oauth_signature_method']) { 192 | case 'HMAC-SHA1': 193 | $request['auth']['oauth_signature'] = base64_encode(hash_hmac('sha1', $signatureBaseString, $key, true)); 194 | break; 195 | default: 196 | // @todo implement the other 2 hashing methods 197 | break; 198 | } 199 | 200 | // Finally, we have all the Authorization header parameters so we can build 201 | // the header string. 202 | $authorizationHeader = 'OAuth'; 203 | 204 | // We don't want to include the realm, method or secrets though 205 | $authorizationHeaderParams = array_diff_key( 206 | $request['auth'], 207 | array_flip(array('method', 'oauth_consumer_secret', 'oauth_token_secret', 'realm')) 208 | ); 209 | 210 | // Add the Authorization header params to the Authorization header string, 211 | // properly encoded. 212 | $first = true; 213 | 214 | if (isset($request['auth']['realm'])) { 215 | $authorizationHeader .= ' realm="' . $request['auth']['realm'] . '"'; 216 | $first = false; 217 | } 218 | 219 | foreach ($authorizationHeaderParams as $name => $value) { 220 | if (!$first) { 221 | $authorizationHeader .= ','; 222 | } else { 223 | $authorizationHeader .= ' '; 224 | $first = false; 225 | } 226 | $authorizationHeader .= $this->authorizationHeaderParamEncode($name, $value); 227 | } 228 | 229 | return $authorizationHeader; 230 | 231 | } 232 | 233 | /** 234 | * Builds an Authorization header param string from the supplied name and 235 | * value. See below for example: 236 | * 237 | * @param string $name E.g. 'oauth_signature_method' 238 | * @param string $value E.g. 'HMAC-SHA1' 239 | * @return string E.g. 'oauth_signature_method="HMAC-SHA1"' 240 | */ 241 | function authorizationHeaderParamEncode($name, $value) { 242 | return $this->parameterEncode($name) . '="' . $this->parameterEncode($value) . '"'; 243 | } 244 | 245 | /** 246 | * Converts an associative array of name => value pairs to a numerically 247 | * indexed array of array('name' => '', 'value' => '') elements. 248 | * 249 | * @param array $array Associative array 250 | * @return array 251 | */ 252 | function assocToNumericNameValue($array) { 253 | $return = array(); 254 | foreach ($array as $name => $value) { 255 | $return[] = array( 256 | 'name' => $name, 257 | 'value' => $value, 258 | ); 259 | } 260 | return $return; 261 | } 262 | 263 | /** 264 | * User defined function to lexically sort an array of 265 | * array('name' => '', 'value' => '') elements by the value of 266 | * the name key, and if they're the same, then by the value of the value key. 267 | * 268 | * @param array $a Array with key for 'name' and one for 'value' 269 | * @param array $b Array with key for 'name' and one for 'value' 270 | * @return integer 1, 0 or -1 depending on whether a greater than b, less than 271 | * or the same. 272 | */ 273 | function sortByNameThenByValue($a, $b) { 274 | if ($a['name'] == $b['name']) { 275 | if ($a['value'] == $b['value']) { 276 | return 0; 277 | } 278 | return ($a['value'] > $b['value']) ? 1 : -1; 279 | } 280 | return ($a['name'] > $b['name']) ? 1 : -1; 281 | } 282 | 283 | /** 284 | * Encodes paramters as per the OAuth spec by utf 8 encoding the param (if it 285 | * is not already utf 8 encoded) and then percent encoding it according to 286 | * RFC3986 287 | * 288 | * @param string $param 289 | * @return string 290 | */ 291 | function parameterEncode($param) { 292 | $encoding = mb_detect_encoding($param); 293 | if ($encoding != 'UTF-8') { 294 | $param = mb_convert_encoding($param, 'UTF-8', $encoding); 295 | } 296 | $param = rawurlencode($param); 297 | $param = str_replace('%7E', '~', $param); 298 | return $param; 299 | } 300 | 301 | } 302 | ?> 303 | -------------------------------------------------------------------------------- /readme.markdown: -------------------------------------------------------------------------------- 1 | Usage instructions (we'll take twitter as an example): 2 | 3 | 1. Grab the code from my github account and add it to app/vendors/http_socket_oauth.php 4 | 5 | 2. Register your application with Twitter (See below if you are developing locally and twitter grumbles about your call back url containing 'localhost') 6 | 7 | 3. Note the consumer key and secret (I add them to Configure in bootstrap) 8 | 9 | 4. Add the following to a controller: 10 | 11 | public function twitter_connect() { 12 | // Get a request token from twitter 13 | App::import('Vendor', 'HttpSocketOauth'); 14 | $Http = new HttpSocketOauth(); 15 | $request = array( 16 | 'uri' => array( 17 | 'host' => 'api.twitter.com', 18 | 'path' => '/oauth/request_token', 19 | ), 20 | 'method' => 'GET', 21 | 'auth' => array( 22 | 'method' => 'OAuth', 23 | 'oauth_callback' => '', 24 | 'oauth_consumer_key' => Configure::read('Twitter.consumer_key'), 25 | 'oauth_consumer_secret' => Configure::read('Twitter.consumer_secret'), 26 | ), 27 | ); 28 | $response = $Http->request($request); 29 | // Redirect user to twitter to authorize my application 30 | parse_str($response, $response); 31 | $this->redirect('http://api.twitter.com/oauth/authorize?oauth_token=' . $response['oauth_token']); 32 | } 33 | 34 | ... replacing with your callback url, i.e. the URL of the page in your application that twitter will redirect the user back to, after they have authorised your application to access their account. In this example, it's the url of the action in the next step. (Note, when you register your app, if you are developing locally, and you tried to enter your callback url with localhost in it, twitter might grumble. A little gem I read somewhere said you can actually create a bit.ly link, add your local callback URL in there, and then add the bit.ly link as the call back url in the twitter application settings. I still add my localhost url in this place though). 35 | 36 | This action fetches a request token from twitter, which it then adds as a query string param to the authorize URL on twitter.com that the user is redirected that prompts them to authorise your app. 37 | 38 | 5. Next add the action for the call back: 39 | 40 | public function twitter_callback() { 41 | App::import('Vendor', 'HttpSocketOauth'); 42 | $Http = new HttpSocketOauth(); 43 | // Issue request for access token 44 | $request = array( 45 | 'uri' => array( 46 | 'host' => 'api.twitter.com', 47 | 'path' => '/oauth/access_token', 48 | ), 49 | 'method' => 'POST', 50 | 'auth' => array( 51 | 'method' => 'OAuth', 52 | 'oauth_consumer_key' => Configure::read('Twitter.consumer_key'), 53 | 'oauth_consumer_secret' => Configure::read('Twitter.consumer_secret'), 54 | 'oauth_token' => $this->params['url']['oauth_token'], 55 | 'oauth_verifier' => $this->params['url']['oauth_verifier'], 56 | ), 57 | ); 58 | $response = $Http->request($request); 59 | parse_str($response, $response); 60 | // Save data in $response to database or session as it contains the access token and access token secret that you'll need later to interact with the twitter API 61 | $this->Session->write('Twitter', $response); 62 | } 63 | 64 | After the user authorises your app, twitter redirects them back to this action, the callback you specified in the previous request. In the querystring are 2 params called 'oauth_token' and 'oauth_verifier'. These, and the consumer key and secret are then sent back to twitter, this time requesting an access token. 65 | 66 | At the end of this action, $response contains an associative array with keys for: 'oauth\_token', 'oauth\_token\_secret', 'user\_id', 'screen\_name'. You should save 'oauth\_token' and 'oauth\_token\_secret' to the session or the database as you need them when you want to access the Twitter API. Then redirect the user to another action, or display a thanks message or tweet to their account or whatever. 67 | 68 | Now if you link to the twitter_connect() action or hit it in your browser address bar, you should be directed off to twitter to authorise your application, and once done, be back within your app with some twitter accounts access tokens. 69 | 70 | Finally, I guess it's useful to know how to do something with the twitter API with this new found power: 71 | 72 | App::import('Vendor', 'HttpSocketOauth'); 73 | $Http = new HttpSocketOauth(); 74 | // Tweet "Hello world!" to the twitter account we connected earlier 75 | $request = array( 76 | 'method' => 'POST', 77 | 'uri' => array( 78 | 'host' => 'api.twitter.com', 79 | 'path' => '1/statuses/update.json', 80 | ), 81 | 'auth' => array( 82 | 'method' => 'OAuth', 83 | 'oauth_token' => $oauthToken, // From the $response['oauth_token'] above 84 | 'oauth_token_secret' => $oauthTokenSecret, // From the $response['oauth_token_secret'] above 85 | 'oauth_consumer_key' => Configure::read('Twitter.consumer_key'), 86 | 'oauth_consumer_secret' => Configure::read('Twitter.consumer_secret'), 87 | ), 88 | 'body' => array( 89 | 'status' => 'Hello world!', 90 | ), 91 | ); 92 | $response = $Http->request($request); 93 | 94 | 95 | Hope you like it. Any issues, please leave on github issue tracker. Any comments, let me know on my blog. Thanks. --------------------------------------------------------------------------------