PHP: REST Client iwith OAuth2 support

I downloaded the server version (PDO) available for the OAuth 2.0 here: http://code.google.com/p/oauth2-php/

Not sure if it is the best implementation out there honestly.

It is configured and currently returns an error JSON indicating it is waiting for a client to pass it the correct arguments.

Now, it comes with a "lib" folder that has a Client .inc file. Honestly, I am not sure how to use it given there is no PHP example I found in the archive and couldn't find anything online. I found an example for Drupal using this library, but it is a mess given they have their own Drupal-related functionalities as a module.

 

 

Setting up an OAuth2 provider is rather easy once you know how the protocol works. It's a 2-or-3 step process (depending on your set-up and whether you're getting tokens on behalf of a user or just from the server).

What you'll need:

  • Working code for an OAuth2 provider
  • Patience

What you'll need to figure out how to do on your code:

  • Create a client (public and private access tokens)
  • Figure out how the authorize and token endpoints are named (typically /authorize and /token)
  • Figure out how the scopes are dealt with

The first step to getting a token is to call /authorize?response_type=code&client_id=[YOUR ID]&redirect_uri=[YOUR REDIRECT URI]&scope=[YOUR SCOPE] , where:

  • clientid ([YOUR ID]) is your public access token
  • redirect_uri ([YOUR REDIRECT URI]) is your redirect URI. You will be redirected to this once you complete the autorize step
  • scope is the scope of your future token

On completion (there's usually a submit button), your browser will be redirected to the URI specified with a code in the URL (code=blah). Save this value.

When you've got this code, call the other endpoint: /token?client_id=[YOUR ID]&client_secret=[YOUR SECRET]&grant_type=authorization_code&scope=[YOUR SCOPE]&code=[YOUR CODE]&redirect_uri=[YOUR REDIRECT URI]

The parameters: - client_id - again, your client public key - client_secret - your private key (this is supposed to be a server-side call) - scope - the scope for the token - MUST MATCH THE FIRST CALL - redirect_uri - the redirect URI - MUST MATCH THE FIRST CALL - code - the code you received

If everything went okay, you'll see a JSON object on your screen containing the token info.

What happens in the background

Step 1 (authorize)

When you confirm the form, the server creates a temporary token (auth token as they're called), which typically has a very short life (my oauth2 sp code typically sets this to 60 seconds). This is the time your server has to go from receiving the code to triggering step 2. It is just a confirmation system, and its purpose is to also store the info provided in step 1 to prevent hijacks.

Step 2 (token)

This is where your access token is actually created. Lots of verifications, lots of stuff, but in the end, the token is just a value that links your client_id and your token. That's all it is.

Shameless plug: if you're using the Laravel framework, I've built exactly this from scratch (rather than using the crappy, undocumented sample code): http://bundles.laravel.com/bundle/oauth2-sp

 


Our client had given me a REST API to which I need to make a PHP call to. But as a matter of fact the documentation given with the API is very limited, so I don't really know how to call the service.

I've tried to Google it, but the only thing that came up was an already expired Yahoo! tutorial on how to call the service. Not mentioning the headers or anything in depth information.

Is there any decent information around how to call a REST API, or some documentation about it? Because even on W3schools, they only describes the SOAP method. What are different options for making rest API in PHP?

 

Use Guzzle. It's a "PHP HTTP client that makes it easy to work with HTTP/1.1 and takes the pain out of consuming web services". Working with Guzzle is much easier than working with cURL.

Here's an example from the Web site:

$client = new GuzzleHttp\Client();
$res = $client->get('https://api.github.com/user', [
    'auth' =>  ['user', 'pass']
]);
echo $res->getStatusCode();           // 200
echo $res->getHeader('content-type'); // 'application/json; charset=utf8'
echo $res->getBody();                 // {"type":"User"...'
var_export($res->json());             // Outputs the JSON decoded data

 


This class can authorize the access of users to an API using the OAuth protocol.

It abstracts OAuth1 (1.0 and 1.0a) and OAuth2 in the same class, so you can use the same code to authorize the access on behalf of the current user any API that supports any version of the OAuth protocol.

It works on Linux, Windows and any other platform without the PECL PHP OAuth extension.

The access tokens are stored by default in session variables, but there are sub-classes specialized in storing the tokens in database tables, files or cookies.

It provides built-in support to several popular OAuth servers, so you do not have to configure the class manually with all OAuth server specific details.

Currently it provides built-in support for many OAuth servers. Every other OAuth server is supported setting end point URLs and other parameters using specific class variables. Additional servers may be supported without changing the main class by configuring a separate JSON configuration file.

The class can also send requests to API using the previously obtained OAuth access token.

It also supports 2 legged API access, so it can send signed API requests that do not require user authorization.

For mobile or other applications that the user cannot be redirected back to the client application site, this class supports pin based authorization either using OAuth 1.0a or OAuth 2.0.

It can as well obtain access tokens for specific users given their user name and password or using client credentials. It supports OAuth 2.0 authorization flows authorization_code, password and client_credentials.

For servers that support offline access like Google and Box.net, the class can also verify if the access token expired and refresh the token value before sending an API call, without requiring the user presence.

For servers that support re-authentication like Facebook, the class may also force the user to enter this application password on the authorization page.

For servers that support revoking access tokens, the class supports this functionality to invalidate a previously retrieved token.

For OpenID Connect servers based on OAuth2, the class decoded and returns the id_token JSON Web Token (JWT), so applications can use the user details such as name and email returned in the id_token response.

 

Details

PHP OAuth Library to Access Any OAuth API

 

The OAuth protocol is not hard to understand but it requires learning about many details and the many differences of operation with different OAuth servers.

OAuth PHP: Solutions

 

PHP has an extension for using OAuth but it practically requires that you learn all the specification documents for all aspects of the OAuth protocol.

Therefore it is better to use a client class like this encapsulate all steps so you do not have to learn so much about the OAuth protocol in all its versions.

PHP OAuth1 Client

 

This PHP class can work with OAuth 1.0 and 1.0a. Despite the class supports servers that work with OAuth 1.0, it is not a secure solution. So most servers that you see and support OAuth 1.0, it is actually OAuth 1.0a which is secure.

PHP OAuth2 Example

 

OAuth 2.0 is not a better version of OAuth 1.0a as if it was an upgrade. You may still see many servers that work securely using OAuth 1.0a.

Nowadays most servers use OAuth 2.0 because it is a protocol version that support more extensions.

The PHP OAuth class either OAuth 1.0, OAuth 1.0a and OAuth 2.0 . For the developer that uses this class, it does not make much difference because the function calls to use are the same.

The main internal difference is that OAuth 1.0a servers return both an access token value and an access token secret.

PHP OAuth Tutorial

 

Several articles have been written to tell not only how to use this package but also to tell about how the different versions of the OAuth protocol work.

You can read all the available tutorial articles in the package blog.

The main tutorial article is entitled PHP OAuth Tutorial on How to Use a Pure PHP OAuth Class with an Example Without using the PECL module Implementation.

OAuth Server PHP Configuration: Setting the PHP OAuth Server Variable to Access Any API

 

This PHP OAuth class can work with any server using OAuth1 or OAuth2. Just change the server variable to the name supported API.

The class provides built-in support for a few common APIs but any new API can be supported by adding a new entry to the oauth_configuration.json file.

This configuration file can be used to presets option values for class variables with the following names. Check the class documentation to learn the meaning of each of these option variables:

oauth_version
dialog_url
reauthenticate_dialog_url
pin_dialog_url
access_token_url
request_token_url
append_state_to_redirect_uri
authorization_header
url_parameters
token_request_method
signature_method
access_token_authentication
access_token_parameter
default_access_token_type
store_access_token_response
refresh_token_authentication
grant_type
access_token_content_type

 

Facebook OAuth2 PHP OAuth Example

 

Here is a simple example of getting the authorization token and making an API call to Facebook Graph API.

Check the complete Facebook OAuth2 PHP OAuth example here.

// Include the necessary class files directly or
// vendor/autoload.php if you used composer to install the package.
require('http.php');
require('oauth_client.php');

$client = new oauth_client_class;
$client->server = 'Facebook';

$client->client_id = 'your application id here';
$client->client_secret = 'your application secret here';

$client->scope = 'email';

if(($success = $client->Initialize()))
{
    if(($success = $client->Process()))
    {
        if(strlen($client->access_token))
        {
            $success = $client->CallAPI(
                'https://graph.facebook.com/v2.3/me?'.
                'fields=id,first_name,last_name,verified,email',
                'GET', array(), array('FailOnAccessError'=>true), $user);
        }
        $success = $client->Finalize($success);
    }
    if($client->exit)
        exit;
}     
if($success)
{
    echo '<h1>', HtmlSpecialChars($user->name), 
        ' you have logged in successfully with Facebook!</h1>';
}
else
{
    echo 'Error: ', HtmlSpecialChars($client->error);
}

 

Vimeo API PHP OAuth Example

 

Here is a simple example of getting the authorization token and making an API call to Vimeo API.

Check the complete Vimeo API PHP example here.

// Include the necessary class files directly or
// vendor/autoload.php if you used composer to install the package.
require('http.php');
require('oauth_client.php');

$client = new oauth_client_class;
$client->server = 'Vimeo';

$client->client_id = 'your application id here';
$client->client_secret = 'your application secret here';

if(($success = $client->Initialize()))
{
   if(($success = $client->Process()))
   {
      if(strlen($client->access_token))
      {
         $success = $client->CallAPI(
            'https://api.vimeo.com/me/?format=json', 
            'GET', array(), array('FailOnAccessError'=>true), $user);
      }
   }
   $success = $client->Finalize($success);
}
if($client->exit)
   exit;
if($success)
{
   echo '<h1>', HtmlSpecialChars($user->name), 
      ' you have logged in successfully with Vimeo!</h1>';
   echo '<pre>', HtmlSpecialChars(print_r($user, 1)), '</pre>';
}
else
{
  echo 'Error: ', HtmlSpecialChars($client->error);
}

 

Google Contacts API PHP Example

 

This example retrieves the Google user contacts using the People API.

Check the complete Google Contacts API PHP example here.

// Include the necessary class files directly or
// vendor/autoload.php if you used composer to install the package.
require('http.php');
require('oauth_client.php');

$client = new oauth_client_class;
$client->server = 'Google';

$client->client_id = 'your application id here';
$client->client_secret = 'your application secret here';

$client->scope = 'https://www.googleapis.com/auth/contacts.readonly';
if(($success = $client->Initialize()))
{
    if(($success = $client->Process()))
    {
        if(strlen($client->authorization_error))
        {
            $client->error = $client->authorization_error;
            $success = false;
        }
        elseif(strlen($client->access_token))
        {
            $success = $client->CallAPI(
                'https://people.googleapis.com/v1/people/me/connections'.
                '?fields=connections(emailAddresses%2Cnames)',
                'GET', array(), array('FailOnAccessError'=>true), $contacts);
        }
    }
    $success = $client->Finalize($success);
}
if($client->exit)
    exit;
if($success)
{
        echo '<pre>';
        foreach($contacts->connections as $contact)
        {
            echo htmlspecialchars($contact->names[0]->displayName), "\n";
        }
        echo '</pre>';
}
else
{
  echo 'Error: ', HtmlSpecialChars($client->error);
}

 

Pinterest API PHP OAuth Example

 

This example retrieves the Pinterest user details using the Pinterst API.

Check the complete Pinterest API PHP example here.

require('http.php');
require('oauth_client.php');

$client = new oauth_client_class;
$client->server = 'Pinterest';

$client->client_id = 'your application id here';
$client->client_secret = 'your application secret here';

$client->scope = 'read_public';
if(($success = $client->Initialize()))
{
    if(($success = $client->Process()))
    {
        if(strlen($client->authorization_error))
        {
            $client->error = $client->authorization_error;
            $success = false;
        }
        elseif(strlen($client->access_token))
        {
            $success = $client->CallAPI(
                'https://api.pinterest.com/v1/me/',
                'GET', array(), array('FailOnAccessError'=>true), $user);
        }
    }
    $success = $client->Finalize($success);
}
if($client->exit)
    exit;
if($success)
{
    echo '<h1>', HtmlSpecialChars($user->data->first_name),
        ' you have logged in successfully with Google!</h1>';
    echo '<pre>', HtmlSpecialChars(print_r($user, 1)), '</pre>';
}
else
{
  echo 'Error: ', HtmlSpecialChars($client->error);
}
Tags