Posts tagged Github

Throughout the Linkey project I’ve been working on a number of PHP libraries that aim to make working with OAuth 2.0 easier.

The library is now at version 2.1, implements the entire core OAuth 2.0 specification and bearer token specification and has had over 1800 installations at the time of writing.

I’m very happy to announce that the University of Lincoln has agreed to transfer ownership of the code to the “PHP League of Extraordinary Packages” which means that it’ll continue to receive updates and be maintained by a number of developers around the world (myself included).

The server repository is now hosted at https://github.com/php-loep/oauth2-server and the client library is now hosted at https://github.com/php-loep/oauth2-client.

I have updated the wikis on both repositories with thorough documentation about how to use each library, and on the server library wiki I’ve added a lot more implementation about how to implement the library for common use cases.

My intention with all the code that has been written as an output of this project was that it would be as easy to use as possible and I’ve had some great feedback from developers:

— “Thanks for making your OAuth 2.0 server library public! It is people like you that make my job slightly more tolerable :)”

— “I wanted to thank you for your awesome library @alexbilbie :)”

— “Thank you for the great posts and lib”

— “If you drink, I will buy you a virtual beer!! What you built is awesome”

And finally in reply to a question that a developer asked me about how to do something with the library:

— “I’m really not surprised it was that simple – you’ve really built this with the end developer in mind. Once again, thanks very much for the info and the repo.”

To conclude I’m really happy with the code, I’ve learnt an awful lot as it has been developed and refined and I’m pleased that it’s new home will ensure long term sustainability.

One of the other PHP libraries I’ve been working for Linkey is a PHP library that makes working with other OAuth 2.0 identity providers “stupidly easy”. I think I’ve done that and it’s time to announce the initial release – https://github.com/lncd/OAuth2-client.

So lets say you want to allow users to sign-in to their Facebook account:

$provider = new \OAuth2\Client\Provider\Facebook(array(
    'clientId'  =>  'XXXXXXXX',
    'clientSecret'  =>  'XXXXXXXX',
    'redirectUri'   =>  'http://your-registered-redirect-uri/'
));

if ( ! isset($_GET['code'])) {

    // If we don't have an authorization code then get one
    $provider->authorize();

} else {

    try {

        // Try to get an access token (using the authorization code grant)
        $t = $provider->getAccessToken('authorization_code', array('code' => $_GET['code']));

        try {

            // We got an access token, let's now get the user's details
            $userDetails = $provider->getUserDetails($t);

            foreach ($userDetails as $attribute => $value) {
                var_dump($attribute, $value) . PHP_EOL . PHP_EOL;
            }

        } catch (Exception $e) {

            // Failed to get user details

        }

    } catch (Exception $e) {

        // Failed to get access token

    }
}

Simple right? If you take out the try/catch statements then it essentially boils down to this:

$provider = new \OAuth2\Client\Provider\<provider name>(array(
    'clientId'  =>  'XXXXXXXX',
    'clientSecret'  =>  'XXXXXXXX',
    'redirectUri'   =>  'http://your-registered-redirect-uri/'
));

if ( ! isset($_GET['code'])) {

    $provider->authorize();

} else {

    $token = $provider->getAccessToken('authorization_code', array('code' => $_GET['code']));
    $userDetails = $provider->getUserDetails($token);
}

The library automatically manages the state parameter to help mitigate cross-site request forgery attacks (where supported by the end-IdP).

At the time of writing there is built in support for Facebook, Google and Github but adding support for other identity providers is trivial – you just need to extend the IdentityProvider class.

I will add support for more providers soon. There also aren’t any unit tests currently but they are coming.

The library is hooked up to Packagist so just add "lncd/oauth2-client": “*” to your composer.json file.

In a previous post I announced my new OAuth 2.0 PHP libraries.

In this post I will show you how to use the server library to secure a simple API with OAuth 2.0.


Install the library

The recommended way of installing the library is via Composer.

If you already have a composer.json file in your root then add ”lncd/oauth2”: “*” in the require object. Then run composer update.

Otherwise create a new file in your project root called composer.json add set the contents to:

{
    "require": {
        "lncd/OAuth2": "*"
    }
}

Now, assuming you have installed Composer run composer install.

Ensure now that you’ve set up your project to autoload composer packages.

You could alternatively add the library as a git submodule or download a zip.

Set up the database

To setup the database just import sql/mysql.sql

Create the storage models

In order to retrieve data from the database you should create classes which implement the following interfaces:

  • \OAuth2\Storage\ScopeInterface
  • \OAuth2\Storage\SessionInterface

Hooking it all up

Setting up the library is simple, just create a new instance of \OAuth2\ResourceServer and pass in your storage models.

// Include the storage models
include 'model_scope.php';
include 'model_session.php';

// Initiate the Request handler
$request = new \OAuth2\Util\Request();

// Initiate the auth server with the models
$server = new \OAuth2\ResourceServer(new SessionModel, new ScopeModel);

Checking for valid access tokens

Before your API responds you need to check that an access token has been presented with the request (either in the query string ?access_token=abcdef or as an authorization header Authorization: bearer abcdef).

If you’re using a framework such as Laravel or CodeIgniter you could use a route filter to do this, or have a custom controller which other controllers extend from. In this example I’m using the Slim framework and I’m going to create a simple route middleware which is run before each endpoint function.

$checkToken = function () use ($server) {

    return function() use ($server)
    {
        // Test for token existance and validity
        try {
            $server->isValid();
        }

        // The access token is missing or invalid...
        catch (\OAuth2\Exception\InvalidAccessTokenException $e)
        {
            $app = \Slim\Slim::getInstance();
            $res = $app->response();
            $res['Content-Type'] = 'application/json';
            $res->status(403);

            $res->body(json_encode(array(
                'error' =>  $e->getMessage()
            )));
        }
    };

};

When $server->isValid() is called the library will run the following tasks:

  • Check if an access token is present in the query string
    • If not, check if a base64 encoded access token is contained in an authorization header.
      • If not, throw \OAuth2\Exception\InvalidAccessTokenException
  • Check if the access token is valid with the database
    • If not, throw \OAuth2\Exception\InvalidAccessTokenException
  • If the access token is valid:
    • Get the owner type (e.g. “user” or “client”) and their ID
    • Get a list of any scopes that are associated with the access token

Assuming an exception isn’t thrown you can then use the following functions in your API code:

  • getOwnerType() – This will return the type of the owner of the access token. For example if a user has authorized another client to use their resources the owner type would be “user”.
  • getOwnerId() – This will return the ID of the access token owner. You can use this to check if the owner has permission to do take some sort of action (such as retrieve a document or upload a file to a folder).
  • hasScope() – You can use this function to see if a specific scope (or several scopes) has been associated with the access token. You can use this to limit the contents of an API response or prevent access to an API endpoint without the correct scope.

A simple example

This example endpoint will return a user’s information if a valid access token is present. If the access token has the user.contact it will return additional information.

$app->get('/user/:id', $checkToken(), function ($id) use ($server, $app) {

    $user_model = new UserModel();

    $user = $user_model->getUser($id);

    if ( ! $user)
    {
        $res = $app->response();
        $res->status(404);
        $res['Content-Type'] = 'application/json';
        $res->body(json_encode(array(
            'error' => 'User not found'
        )));
    }

    else
    {
        // Basic response
        $response = array(
            'error' => null,
            'result'    =>  array(
                'user_id'   =>  $user['id'],
                'firstname' =>  $user['firstname'],
                'lastname'  =>  $user['lastname']
            )
        );

        // If the acess token has the "user.contact" access token include
        //  an email address and phone numner
        if ($server->hasScope('user.contact'))
        {
            $response['result']['email'] = $user['email'];
            $response['result']['phone'] = $user['phone'];
        }

        // Respond
        $res = $app->response();
        $res['Content-Type'] = 'application/json';

        $res->body(json_encode($response));
    }

});

Limiting an endpoint to a specific owner type

In this example, only a user’s access token is valid:

$app->get('/user', $checkToken(), function () use ($server, $app) {

    $user_model = new UserModel();

    // Check the access token's owner is a user
    if ($server->getOwnerType() === 'user')
    {
        // Get the access token owner's ID
        $userId = $server->getOwnerId();

        $user = $user_model->getUser($userId);

        // If the user can't be found return 404
        if ( ! $user)
        {
            $res = $app->response();
            $res->status(404);
            $res['Content-Type'] = 'application/json';
            $res->body(json_encode(array(
                'error' => 'Resource owner not found'
            )));
        }

        // A user has been found
        else
        {
            // Basic response
            $response = array(
                'error' => null,
                'result'    =>  array(
                    'user_id'   =>  $user['id'],
                    'firstname' =>  $user['firstname'],
                    'lastname'  =>  $user['lastname']
                )
            );

            // If the acess token has the "user.contact" access token include
            //  an email address and phone numner
            if ($server->hasScope('user.contact'))
            {
                $response['result']['email'] = $user['email'];
                $response['result']['phone'] = $user['phone'];
            }

            // Respond
            $res = $app->response();
            $res['Content-Type'] = 'application/json';

            $res->body(json_encode($response));
        }
    }

    // The access token isn't owned by a user
    else
    {
        $res = $app->response();
        $res->status(403);
        $res['Content-Type'] = 'application/json';
        $res->body(json_encode(array(
            'error' => 'Only access tokens representing users can use this endpoint'
        )));
    }

});

You might use an API function like this to allow a client to discover who a user is after they’ve signed into your authorization endpoint (see an example of how to do this here).

Limiting an endpoint to a specific owner type and scope

In this example, the endpoint will only respond to access tokens that are owner by client applications and that have the scope users.list.

$app->get('/users', $checkToken(), function () use ($server, $app) {

    $user_model = new UserModel();

    $users = $user_model->getUsers();

    // Check the access token owner is a client
    if ($server->getOwnerType() === 'client' && $server->hasScope('users.list'))
    {
        $response = array(
            'error' => null,
            'results'   =>  array()
        );

        $i = 0;
        foreach ($users as $k => $v)
        {
            // Basic details
            $response['results'][$i]['user_id'] = $v['id'];
            $response['results'][$i]['firstname'] = $v['firstname'];
            $response['results'][$i]['lastname'] = $v['lastname'];

            // Include additional details with the right scope
            if ($server->hasScope('user.contact'))
            {
                $response['results'][$i]['email'] = $v['email'];
                $response['results'][$i]['phone'] = $v['phone'];
            }

            $i++;
        }

        $res = $app->response();
        $res['Content-Type'] = 'application/json';

        $res->body(json_encode($response));
    }

    // Access token owner isn't a client or doesn't have the correct scope
    else
    {
        $res = $app->response();
        $res->status(403);
        $res['Content-Type'] = 'application/json';
        $res->body(json_encode(array(
            'error' => 'Only access tokens representing clients can use this endpoint'
        )));
    }

});

You might secure an endpoint in this way to only allow specific clients (such as your applications’ main website) access to private APIs.


Hopefully you will see how easy it is to secure an API with OAuth 2.0 and how you can use scopes to limit response contents or access to endpoints.

You can download a complete working example here – https://github.com/lncd/oauth2-example-resource-server.

Over the last few months I’ve been developing a PHP library that helps you work with OAuth 2.0 in a number of different ways:

  • Develop an authentication server which can be used as part of a web “single sign on” solution.
  • Secure your APIs with access tokens and scopes.
  • Easily sign users in to many different OAuth 2.0 identity providers.

The code for the authentication and resource server can be found on Github here https://github.com/lncd/OAuth2.

The server library code requires PHP 5.3+, is hooked into Packagist (a bit like Ruby Gems but for PHP) and has 100% unit test code coverage. It has built in support for the following grants:

You can easily create you own grants by extending \OAuth2\Grant\GrantInterface. I’m going to be creating plugins which support JSON web tokens and the SAML assertions.

The code for the client library can be found here https://github.com/lncd/OAuth2-Client – at the time of writing it isn’t quite finished, I’ll blog when it is.

Over the next few blog posts I’ll document how to use the libraries.