How to use Socialite package with Laravel
Tags: laravel, php, oauth
Published: 2022-08-16 07:19:02

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](https://laravel.com/docs/9.x/socialite) 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:

```bash
composer require socialiteproviders/github
```

## 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 :

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

## 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',`.

```php
protected $listen = [
    \SocialiteProviders\Manager\SocialiteWasCalled::class => [
        // ... other providers
        \SocialiteProviders\GitHub\GitHubExtendSocialite::class.'@handle',
    ],
];
```

## 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.

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

## 5. Usage on your application

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

```php
return Socialite::driver('github')->redirect();
```

In [laravel documentation](https://laravel.com/docs/9.x/socialite), 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 :

```php
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
});
```

## 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 :

```php
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');
});
```

Now you have add the OAuth2 authentication to your application. Don't hesitate to have a look at the [Laravel doc](https://laravel.com/docs/9.x/socialite) and the [package doc](https://socialiteproviders.com/usage/#_1-installation) to see all the possibilities