Laravel Socialite Custom Providers

With the Laravel 5 release being any second now, a lot of people are going to start using the laravel/socialite functionality. This library allows you to add SSO to your projects with just a few lines of code.

Pre requisite: Read the docs on Socialite

However: Socialite currently supports authentication with Facebook, Twitter, Google, and GitHub.

So what if you wanted to support oAuth from other providers — for example Spotify? In this tutorial I’ll show you how…

Step 1: Create a new provider for your oAuth provider

The first step is to dive in and see how one of the existing providers work. From looking at GithubProvider we can see that we need to implement the ProviderInterface and we can also extend the AbstractProvider as a shortcut to common oAuth 2 functionality.

Step 2: Implement the abstract methods from the AbstractProvider

From looking at AbstractProvider, the methods we need to implement are:

  • getAuthUrl($state)
  • getTokenUrl()
  • getUserByToken($token)
  • mapUserToObject(array $user)

Looking at the example from GitHub, we can easily implement this in our SpotifyProvider class.

You’ll also notice, we’ve overridden a couple of additional methods from the AbstractProvider class to handle the intricacies of the Spotify oAuth implementation.

  • formatScopes(array $scopes) — separate with spaces instead of commas
  • getAccessToken($code) — use Basic auth when calling Spotify
  • getTokenFields($code) — add grant_type field when requesting a token

In addition, we can add constants for all the different scopes that Spotify provides via oAuth. This will make it easier for us down the line to specify the scopes that we want.

Later, we will see how the application can choose what scopes to request.

Step 3: Setup config like normal in config/services.php

The redirect property requires the full URL and we can’t use the url() function here as it will cause errors when running Laravel via the console. For this reason I like to add a URL to my .env file and reference it here, as the URL is environment specific anyway (I also reference it in my config/app.php for consistency).

Step 4: Add Spotify into Socialite

Since the interface to use Socialite is extended from the Manager class, we can use the extend method to add the “spotify” driver in to the mix.

The best place to put this function is probably in your AppServiceProvider.php and call it from the boot() method.

Step 5: Create the controller and routes to do the HTTP stuff

The controller methods…

And the routes…

Conclusion

You can also apply the same methodologies for any sort of authentication provider, as long as you implement the Provider contract.

Perhaps someone in the community will implement some for SAML or OpenID (if you could find a provider that still uses them :p)