OAuth and PHP

As in another article I presented how to just use OauthBase.cs in .net to implement oauth both in service and client. Here is my example of php equivalent.It just uses Andy Smith’s basic PHP library for OAuth from here

The point is to demonstrate what oauth is all about and how easy to implement it, even though the examples are about 2 legged ones, but 3 legged oauth is very similar.

Example of an oauth client

require 'OAuth.php';

$key = 'key';
$secret = 'secret';
$consumer = new OAuthConsumer($key, $secret);


$api_endpoint ='http://localhost:49262/TestProject/Service2.svc/user/123';

//handle request in 'server' block above
$parameters = array();

//use oauth lib to sign request
$req = OAuthRequest::from_consumer_and_token($consumer, null, "GET", $api_endpoint, $parameters);

$sig_method = new OAuthSignatureMethod_HMAC_SHA1();

$req->sign_request($sig_method, $consumer, null);//note: double entry of token

//get data using signed url
$ch = curl_init($req->to_url());

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 
$responsefromwcf = curl_exec($ch);

curl_close($ch);

A couple of points:

1. Token is null which is only needed for 3 legged where a token exists

2. sign_request should be done as last step before request sent out

3. All normal GET or POST params must be put into $parameters before sign, as they are part of base string which is to be signed by consumer secret

4. Oauth parameters are actually attached in query, rather than in headers both are valid.

5. A call like this will be generated:

http://localhost:49262/TestProject/Service.svc/user/123?oauth_consumer_key=key&oauth_nonce=10a33ed37b549301644b23b93fc1f1c5&oauth_signature=cUobFDxVB5wjPe9X2XICJ6awmnE%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1289976718&oauth_version=1.0

Example of service server:

require 'OAuth.php';

$key = 'key';
$secret = 'secret';

$method = $_SERVER['REQUEST_METHOD'];
  $uri = 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].$_SERVER['REQUEST_URI'];
  $sig = $_GET['oauth_signature'];
  
  $consumer = new OAuthConsumer($_GET['oauth_consumer'], $secret);
  $sig_method = new OAuthSignatureMethod_HMAC_SHA1;


  $req = new OAuthRequest($method, $uri);
  
  //token is null because we're doing 2-leg
  $authenticated = $sig_method->check_signature($req, $consumer, null, $sig );

All it is doing is just double check the hash is the same as passed in sig, this authentication is done before service actually starts to process request.

Here is an example how it is done in dotnet

Tags:

This entry was posted on Wednesday, November 17th, 2010 at 9:17 am and is filed under PHP. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

One Response to “OAuth and PHP”

  1. Francis says:

    Hello
    Good post, I wanted to consult you as it should do the validation if you have a list of keys in a database
    Thanks

Leave a Reply

*