Easily integrate other OAuth 2.0 identity providers with PHP

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.