Skip to content

Instantly share code, notes, and snippets.

@lsloan
Last active May 19, 2016 17:15
Show Gist options
  • Select an option

  • Save lsloan/6774f2b7bdff25ef976dfe08337fdd0e to your computer and use it in GitHub Desktop.

Select an option

Save lsloan/6774f2b7bdff25ef976dfe08337fdd0e to your computer and use it in GitHub Desktop.
An example of using a popular PHP OAuth package (eher/oauth) to generate the value of the HTTP Authorization header for a request.

OAuth support isn't included with PHP. It's the developer's responsibility to install an appropriate package.

Solutions from Composer

  1. https://packagist.org/packages/eher/oauth

    This is the package used by the example code in this repository. Its API isn't well-documented, but it wasn't difficult to figure out.

  2. https://packagist.org/packages/lusitanian/oauth

    This package was considered for this example, but its API wasn't as easy to understand as that of eher/oauth. It may be worthwhile to further investigate using this package, considering its higher popularity. (1,126,505 downloads for this package, versus 130,129 for eher/oauth.) This package's popularity partly comes from its inclusion of code for using OAuth 2.0 with many popular services.

Official PHP solutions

  1. https://pecl.php.net/package/oauth

    This package requires the PHP source code to compile it and special user privileges to install it.

  2. https://pear.php.net/package/HTTP_OAuth

    This is a pure-PHP OAuth package. Although it doesn't need to be compiled, it still needs special user provileges to install it.

{
"require": {
"eher/oauth": "1.0.7"
}
}
<?php
require_once 'vendor/autoload.php';
/**
* Why doesn't PHP already have these defined?
*/
class HttpMethods {
const
HTTP_METHOD_DELETE = 'DELETE',
HTTP_METHOD_GET = 'GET',
HTTP_METHOD_HEAD = 'HEAD',
HTTP_METHOD_POST = 'POST',
HTTP_METHOD_PUT = 'PUT';
}
$requestUrl = 'http://oauth-protected.example.org/';
$requestMethod = HttpMethods::HTTP_METHOD_GET;
$consumerKey = '_your_consumer_key_here_';
$consumerSecret = '_your_consumer_secret_here_';
$consumer = new Eher\OAuth\Consumer($consumerKey, $consumerSecret);
$token = null;
$signatureMethod = new Eher\OAuth\HmacSha1();
$request = Eher\OAuth\Request::from_consumer_and_token(
$consumer, $token, $requestMethod, $requestUrl
);
$request->sign_request($signatureMethod, $consumer, $token);
$authorizationHeaderValue = substr($request->to_header(), 15); // Skip "Authorization: " part
echo $requestUrl . PHP_EOL;
echo $authorizationHeaderValue . PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment