Friday, January 24, 2014

Repost: Two Leg OAuth Authentication For Layar in PHP

This isn't my content, but the original by mobius was offline. Here's a copy from the waybackmachine.

Well it took me like few hours to get this to work, so I am sharing my solution in case anyone gets in the same place I was.
Initially, I should tell you that I tried php-oauth ( which is probably the most complete library I found for PHP, but too complicated for what I wanted to do.
I also tried the PECL extension of PHP, ( in which, in version 1.0.0 I was unable to get OAuthProvider to perform a Two Leg Authentication. (I think there might be a bug having to do with passing callback functions as arrays – part of the class)
So eventually I found another OAuth library ( that I could get a super striped down server to actually work (
Long story short, use this code in your layer to authenticate layar service:
require_once 'OAuth.php';
$key = 'xxxxxxxx';        // Set this accordingly both here and to the Layar layer configuration
$secret = 'xxxxxxxxx';
$consumer = new OAuthConsumer($key, $secret);
$signature = new OAuthSignatureMethod_HMAC_SHA1();
$request = new OAuthRequest( $_SERVER['REQUEST_METHOD'], 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'] );
if( !($valid = $signature->check_signature( $request, $consumer, null, $_REQUEST['oauth_signature'])) ) {
As mentioned by Rasmus on his really good tutorial on PECL OAuth extension ( a nice and pretty secure way to generate the secret/key pair for OAuth to use could be the following snippet:

$fp = fopen('/dev/urandom','rb');
$entropy = fread($fp, 32);
// in case /dev/urandom is reusing entropy from its pool, let's add a bit more entropy
$entropy .= uniqid(mt_rand(), true);
$hash = sha1($entropy);  // sha1 gives us a 40-byte hash
// The first 30 bytes should be plenty for the consumer_key
// We use the last 10 for the shared secret
I just wish someone at Layar mentioned somewhere that this is a “Two-Leg” authentication for us that were not familiar with OAuth. It would have saved me a lot of time searching for the right answer :)
Post a Comment