DEV Community 👩‍💻👨‍💻

Judicaël
Judicaël

Posted on

How to use Socialite package with Laravel

Today many sites use OAuth2 authentication, so that users can authenticate with their Google, Facebook, Microsoft, etc. accounts.

OAuth 2.0 is an authorization framework that will allow a third-party application to access a web service. As web and mobile applications have become more and more democratic, different applications are likely to interact with each other. For example, a website A could use the data of a known social network to register a user.

Thus, the user allows giving access to his personal information already available on the social network to the website A.

Here is a brief summary of OAuth2, I will talk about it in more details in another article.

Now that you know a bit more about OAuth2, I'll show you how to integrate it in your Laravel applications. To integrate it in your applications, there is nothing complicated, you just have to use the Socialite package which is indicated in the document of Laravel.

Here are the steps to follow to use OAuth2 on a Laravel application:

Package installation and configuration :

1. Installation :

In first execute this command to install the provider, for exemple Github:

composer require socialiteproviders/github
Enter fullscreen mode Exit fullscreen mode

2. Service provider :

In config/app.php add \SocialiteProviders\Manager\ServiceProvider::class to your providers[] array, and remove Laravel\Socialite\SocialiteServiceProvider from your providers[] if you have added it already.

For example :

'providers' => [
    // a whole bunch of providers
    // remove 'Laravel\Socialite\SocialiteServiceProvider',
    \SocialiteProviders\Manager\ServiceProvider::class, // add
];
Enter fullscreen mode Exit fullscreen mode

3. Event listener

  • Add SocialiteProviders\Manager\SocialiteWasCalled event to your listen[] array in app/Providers/EventServiceProvider.
  • Add your listeners (i.e. the ones from the providers) to the SocialiteProviders\Manager\SocialiteWasCalled[] that you just created.
  • Add the listener for your provider to the array. In our example, this is \SocialiteProviders\GitHub\GitHubExtendSocialite::class.'@handle',.
protected $listen = [
    \SocialiteProviders\Manager\SocialiteWasCalled::class => [
        // ... other providers
        \SocialiteProviders\GitHub\GitHubExtendSocialite::class.'@handle',
    ],
];
Enter fullscreen mode Exit fullscreen mode

4. Configuration

Before using Socialite, you will need to add credentials for the OAuth providers your application utilizes. These credentials may be retrieved by creating a “developer application” within the dashboard of the service you will be authenticating with

Then add credentials in the config/services.php file.

'github' => [
    'client_id' => env('GITHUB_CLIENT_ID'),
    'client_secret' => env('GITHUB_CLIENT_SECRET'),
    'redirect' => 'http://example.com/callback-url',
],
Enter fullscreen mode Exit fullscreen mode

5. Usage on your application

You should now be able to use it (assuming you have the facade installer) :

return Socialite::driver('github')->redirect();
Enter fullscreen mode Exit fullscreen mode

In laravel documentation, to authenticate users with an OAuth provider, you will need two routes : one for redirecting the user to the OAuth provider, and another for receving the callback from the provider after authentication :

use Laravel\Socialite\Facades\Socialite;

Route::get('/auth/redirect', function () {
    return Socialite::driver('github')->redirect();
});

Route::get('/auth/callback', function () {
    $user = Socialite::driver('github')->user();

    // $user->token
});
Enter fullscreen mode Exit fullscreen mode

6. Authentication and storage

When the user has been retrieved from the OAuth provider, you can determine if the user exits in your application’s database and authenticate the use. If he does not exist in the database, you will create a new record to represent the user :

use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;

Route::get('/auth/callback', function () {
    $githubUser = Socialite::driver('github')->user();

    $user = User::updateOrCreate([
        'github_id' => $githubUser->id,
    ], [
        'name' => $githubUser->name,
        'email' => $githubUser->email,
        'github_token' => $githubUser->token,
        'github_refresh_token' => $githubUser->refreshToken,
    ]);

    Auth::login($user);

    return redirect('/dashboard');
});
Enter fullscreen mode Exit fullscreen mode

Now you have add the OAuth2 authentication to your application. Don't hesitate to have a look at the Laravel doc and the package doc to see all the possibilities

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.