Installing OCLC's PHP Authentication Library

Before I get to the meat of this blog post—how to install OCLC’s PHP Authentication Library—I thought I’d take a moment to introduce myself. I’m Hank Sway, a new Product Analyst at OCLC for the WorldShare Platform APIs. I’ve worked in a number of library technology settings, including as a director of IT in a public library and a systems librarian in academia. I’m really excited to have joined OCLC and for this opportunity to focus on API development, a long-time geeky passion of mine.

Now that that’s over with, I’ll start by pointing you to the OCLC Developer Network GitHub, where you can find our Authentication Libraries in a variety of languages (PHP, Python, Ruby) as well as demo apps. These libraries are wrappers around the Web Service Authentication system that is used by OCLC’s web services. If you’re planning to write an application that interacts with our APIs, believe me when I say that the Authentication Libraries will make your life a lot easier.

I’m now going to go through a few environment-setup steps that may seem basic to experienced developers, but they should be helpful for those just starting to write code that interfaces with web services. First, if you’re working on your local machine, you’ll need to make sure you have a web server stack installed. Without this, you won’t be able to run PHP code locally. I personally recommend MAMP, which has a simple point-and-click installer and GUI.

You’ll also need to set up Git (on a Mac, the Xcode developer tool package takes care of this for you) and a text editor. Every developer has their preference; mine is Sublime Text.

Also, make sure your system is pointing to the latest version of PHP that you installed with MAMP (or your preferred web server). To do this, create or edit the .bash_profile file in your user directory, and make sure it contains a line referencing your web server’s PHP executable. For example:

export PATH=/Applications/MAMP/bin/php/php7.0.12/bin:$PATH

Now, you’re ready to start following the instructions in the README on GitHub. We’re going to use a PHP dependency manager called Composer to install the Authentication Library and the other services it relies on. Start by creating a directory for your project (mine is called hank-auth-php) and a file in that directory called composer.json. That file should contain the following text:

{
  "name" : "MyApp",
  "repositories":
  [
    {
      "type": "git",
      "url": "https://github.com/OCLC-Developer-Network/oclc-auth-php.git"
    }
  ],
  "require" :
  {
    "OCLC/Auth" : ">=3.0"
  }
}

This text, in JSON format, tells Composer that your application requires the PHP Authentication Library and where to get it. But first, we need to download and install Composer. Issue the following command to do so:

$ curl -s https://getcomposer.org/installer | php

Then, run this command to tell Composer to install the Authentication Library and its dependencies:

$ php composer.phar install

The Authentication Library’s dependencies include a package called Guzzle, which is used to send HTTP requests. If your system is referencing an old version of PHP, you may see errors like the following:

- OCLC/Auth 2.0 requires lib-openssl * -> the requested linked library openssl has the wrong version installed or is missing from your system, make sure to have the extension providing it.

Updating your .bash_profile as suggested above should fix this problem, but if you encounter any errors at this stage, it will likely help to check your phpinfo() page. One way to do so is to create a file called phpinfo.php in your project directory, containing the following code:

<?php
  phpinfo();
?>

Then, you’ll need to start up your web server. I like to use my project directory as the document root. In MAMP, this is specified under Preferences > Web Server > Document Root. If you do so and follow MAMP’s other default settings, you’ll go to this URL to see your phpinfo() page:

            http://localhost:8888/phpinfo.php

This (stunningly beautiful) page will give you more information than you could ever dream of about your PHP installation, including which versions of which PHP extensions (e.g., curl, openssl) are installed. If you’re encountering any errors about missing dependencies, you can likely confirm what’s going on here.

With that, we’re finally ready to start writing code!

I’m going to walk through a basic example that we provide on GitHub, which makes use of the PHP Authentication Library to send a request to the WorldCat Metadata API. OCLC’s APIs support authentication and authorization via three distinct methods: WSKey Lite, HMAC Signatures, and Access Tokens. The Authentication Libraries are particularly useful when using the two more advanced methods (HMAC Signatures and Access Tokens). This particular example uses an HMAC Signature.

To get started, create a file in your project directory called index.php, and copy in the following code:

<?php
  require_once('vendor/autoload.php');
  use OCLC\Auth\WSKey;
  use OCLC\User;
  use GuzzleHttp\Client;
  use GuzzleHttp\Exception\RequestException;

  $key = 'api-key';
  $secret = 'api-key-secret';
  $wskey = new WSKey($key, $secret);

  $url = 'https://worldcat.org/bib/data/823520553?classificationScheme=LibraryOfCongress&holdingLibraryCode=MAIN';

  $user = new User('128807', 'principalID', 'principalIDNS');
  $options = array('user'=> $user);

  $authorizationHeader = $wskey->getHMACSignature('GET', $url, $options);

  $client = new Client(
    [
    'curl' => [
      CURLOPT_SSLVERSION => '3'
    ]]
  );
  $headers = array();
  $headers['Authorization'] = $authorizationHeader;

  try {
    $response = $client->request('GET', $url, ['headers' => $headers]);
    echo $response->getBody(TRUE);
  } catch (RequestException $error) {
    echo $error->getResponse()->getStatusCode();
    echo $error->getResponse()->getBody(true);
  }
?> 

What’s going on here? Let’s go through section by section.

<?php
  require_once('vendor/autoload.php');
  use OCLC\Auth\WSKey;
  use OCLC\User;
  use GuzzleHttp\Client;
  use GuzzleHttp\Exception\RequestException;

This code begins the PHP program and initializes the required libraries, including the Authentication Library, which Composer has magically stored for you in the vendor directory it created.

$key = 'api-key';
$secret = 'api-key-secret';
$wskey = new WSKey($key, $secret); 

Next, we need to create a WSKey object using your OCLC Web Service credentials. WSKey is a class in the Authentication Library that represents an OCLC Web Service Key. You’ll need to insert your API Key and Secret into 'api-key' and 'api-key-secret' respectively (retaining the single quotes).

In order for this example to work, your WSKey must be authorized for the WorldCat Metadata API Service. You can find these details in OCLC’s WSKey Management system; if you don’t already have a WSKey, you can request one there as well after logging in.

$url = 'https://worldcat.org/bib/data/823520553?classificationScheme=LibraryOfCongress&holdingLibraryCode=MAIN';

This line is the WorldCat Metadata API request URL that this demo will use as an example. You can substitute any valid WorldCat Metadata API request URL here. OCLC’s API Explorer is a great place to learn about the different types of queries that are supported and to test them out to make sure you’re using the correct syntax. The example URL I’m using reads a master bibliographic record (OCLC Number 823520553) from WorldCat and displays the output in MARCXML format.

In addition to application-level authentication and authorization, some OCLC web services, including the WorldCat Metadata API, perform verification at the user level. There are several ways to achieve this; in this example, we’ll build an HMAC Signature.

$user = new User('128807', 'principalID', 'principalIDNS');

We start by creating a User object called $user, which represents your OCLC user account. The first parameter, 128807, is the Registry ID of the Sandbox Institution, which I am using because I am using a Sandbox WSKey. (If you are using a Production WSKey, you will need to supply your institution’s Registry ID, which you can find in the Directory of OCLC Members.)

There are several ways to obtain principalID and principalIDNS values, which you can find more information about on our user-level authentication page. Your principalID will be a string that looks something like 8eab9f92-3951-431c-975a-d7dfkd9rd131. Your principalIDNS will be urn:oclc:wms:da if you’re using a WorldShare Management Services account.

$options = array('user'=> $user);
$authorizationHeader = $wskey->getHMACSignature('GET', $url, $options);

Now that we’ve created the User object, we insert it in an array called $options in order to create the HMAC Signature we’ll use to send the HTTP request to the API. To do so, we use the getHMACSignature method in the WSKey class, and store the result in a variable called $authorizationHeader.

$client = new Client(
  [
    'curl' => [
      CURLOPT_SSLVERSION => '3'
  ]]
);
$headers = array();
$headers['Authorization'] = $authorizationHeader;

With our HMAC Signature created, we can now use Guzzle’s Client class to build the HTTP request itself. Note that we’re embedding the HMAC Signature ($authorizationHeader) in the $headers array.

Having built the HTTP request, it’s now time to send it! That’s exactly what this code does:

  try {
    $response = $client->request('GET', $url, ['headers' => $headers]);
    echo $response->getBody(TRUE);
  } catch (RequestException $error) {
    echo $error->getResponse()->getStatusCode();
    echo $error->getResponse()->getBody(true);
  }
?>

If the request is successful, the WorldCat Metadata API’s response will display. If you start your web server and point a browser to your index.php file (using http://localhost:8888/ or the like), you should see this: 

file

If the request to the API is not successful, an error will display. Generic browser warnings are often not very helpful, so I would recommend setting display_errors to On in your php.ini configuration file. (To find the location of this file, check your phpinfo() page.) If you do so and there’s a problem with your request, you’ll at least see a more meaningful error message, like this:

file

That way, you’ll at least know that the problem has something to do with the credentials you’re supplying to the API.

Here’s one last tip that illustrates the beauty of installing dependencies with Composer. When it comes time to update your dependencies, simply run the following command from your project directory:

$ php composer.phar update 

This tells Composer to check for newer versions of your application’s dependencies and install them if available. You may see output like this:

file

With that, I’ll wrap up this post. I hope that this has been helpful in showing how OCLC’s Authentication Libraries can simplify authentication and authorization when writing code that interacts with our web services. If you run into problems not covered here, or have other questions or comments about our APIs, we’re always happy to hear from you at devnet@oclc.org. Thank you for reading!

  • Hank Sway

    Hank Sway

    Product Analyst

    O: +1-614-764-6817