Here I will post all my system settings and configurations to test it out.
Prerequisite
System
- CentOS 6.3
- PHP 5.3.18
- PECL Oauth extension (via command pecl install oauth)
- Drupal-7.17
- Server URL: http://core.zeus.lan (you can use any URL BUT You SHOULD really going for HTTPS)
- Client URL: http://localhost/oauth.php (this will be used below)
Modules
Step-by-Step
I use location sites/all/modules/contrib for my drupal modules.
Services Configuration
First we set up the services with oauth.
- In Drupal site, install modules: REST Server, OAuth Authentication, OAuth Provider UI.
- In Drupal directory, comment out line 6 to 8 in file oauth/lib/OAuth.php, since it will conflict with PECL OAuth.
- In Drupal site, Create OAuth context in admin/config/services/oauth/add, make sure to create Authorization level and set as default.
- Then add Services myawesomejson in admin/structure/services/add, choose Server:REST, Path to endpoint:myawesomejson, tick OAuth authentication , then hit Save.
- Next, click Edit Resources for your earlier json services, check all resources, then hit Save.
- Next, click tab:Server, check all boxes, then hit Save.
- Lastly, click tab:Authentication, use your earlier OAuth Context, and Default required authentication: select Three Leg or Two Leg, then hit Save.
Consumer Creation
Finally we ready to create the consumer and finish our server session. For this tutorial, I use admin account.
- Go to My Account (URL /user) and click tab:Authorization.
- Click Add consumer and make sure Callback URL is Client URL above, then hit Save.
- Edit your Consumer, and click Show Secret. Note the Consumer Key and Consumer Secret which will be used for PHP Client below.
PHP Client for 3-legged OAuth
For the PHP Client, I copy paste the code from http://id1.php.net/manual/en/oauth.examples.fireeagle.php, I change the variables into:
$req_url = 'http://core.zeus.lan/oauth/request_token';
$authurl = 'http://core.zeus.lan/oauth/authorize';
$acc_url = 'http://core.zeus.lan/oauth/access_token';
$api_url = 'http://core.zeus.lan/myawesomejson';
$conskey = 'your_consumer_key';
$conssec = 'your_consumer_secret';
Now visit your Client URL, you'll redirected to the Server URL, and after clicking Grant button, you'll back to your Client URL with result like below:
Array ( [0] => stdClass Object ( [uid] => 1 [name] => admin .... etc etc
PHP Client for 2-legged OAuth
A more simple (modified from above file), make sure you select 2-Legged in your Services Authentication.
Full code here:
$api_url = 'http://core.zeus.lan/myawesomejson';
$conskey = 'your_consumer_key';
$conssec = 'your_consumer_secret';
session_start();
try {
$oauth=new OAuth($conskey,$conssec,OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_URI);
$oauth->enableDebug();
$oauth->fetch("$api_url/user.json");
$json = json_decode($oauth->getLastResponse());
print_r($json);
} catch(OAuthException $E) {
print_r($E);
}
Also more detailed version can be accessed at my blog here.