Jens Segers on

Laravel OAuth client

David Desberg, also known as Lusitanian, has created an awesome OAuth 1 and 2 client, so I decided to integrate it into Laravel. His library has support for 34 services, including all the mayor services like Facebook, Twitter, Google, Amazon, ... Go check out the result on GitHub.

To integrate it into Laravel, I decided to use the new services configuration file that was introduced with Laravel 4.2 and take advantage of Laravel's session configuration. This way, if you have configured your application to store session data in a database or redis, the library will do it as well.

To install the package, run the following command or manually add it to your composer.json file:

composer require jenssegers/oauth:*

Then add the service provider and an alias to your app/config/app.php configuration file:

'Jenssegers\OAuth\OAuthServiceProvider',

The alias:

'OAuth'            => 'Jenssegers\OAuth\Facades\OAuth',

To add services to your configuration, edit your app/config/services.php file and add an oauth consumer:

'facebook' => [
    'client_id'     => 'my-client-id',
    'client_secret' => 'my-client-secret',
    'scope'         => [],
]

That's basically it, now you can create a service instance to interact with its API like this:

$facebook = OAuth::consumer('facebook');

By default it will use the current URL as the redirect url, but if you want to override the url or the scope, you can pass them as additional parameters:

$facebook = OAuth::consumer('facebook', URL::to('url'), ['email', 'publish_actions']);

You can find a full example on how to interact with the Facebook API on GitHub. Also, you can check out the examples in the original library for some extra guidance.

Webmentions

Tweet about this blog post and you will appear below!