Laravel 6 Socialite Login with Facebook Google Twitter and Github

Laravel Socialite currently supports authentication with Facebook, Twitter, LinkedIn, Google, GitHub, GitLab and Bitbucket. In this tutorial we will see how to create authentication system in our apps using Laravel socialite package. 

Socialite from laravel makes it very easy to add multiple providers for authentication, in this post lets build an Auth system on top of Laravel’s default Authentication to support login and signup using Facebook, Google, Twitter and Github.

In this tutorial i am going to discuss step by step how to login using laravel socialite packages. We will see laravel social login with facebook, google, twitter and github also.

You can visit to know more information about laravel socialite from alravel official website.

laravel-socialite-example-from-scratch

Let's start laravel social login example tutorial.

Step 1 : Installation 

To get started with Socialite, use Composer to add the package to your project's dependencies:

composer require laravel/socialite

Step 1 : Configuration

Now add this into providers and aliases array in config/app.php file. 

config/app.php

'providers' => [
    Laravel\Socialite\SocialiteServiceProvider::class,
]

'aliases' => [
    'Socialite' => Laravel\Socialite\Facades\Socialite::class,
]

Step 3 : Create Migration

Now let’s add some fields in our user’s migration provided by laravel to store avatar and provider info along with access_token. Add this to our default users table.

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');

        $table->string('avatar')->nullable();
        $table->string('provider', 20)->nullable();
        $table->string('provider_id')->nullable();
        $table->string('access_token')->nullable();

        $table->rememberToken();
        $table->timestamps();
    });
}

After this run following command to complete our migration.

php artisan migrate

 and open app/User.php model to add these fields in fillable property so we can mass assign them later.

app/User.php

protected $fillable = [
     'name', 'email', 'password',
     'avatar', 'provider_id', 'provider',
     'access_token'
];

//You can also use below statement 

protected $guarded = ['*'];

Step 4 : Create Oauth App

Before using Socialite, you will also need to add credentials for the OAuth services your application utilizes. These credentials should be placed in your config/services.php configuration file.

You should use the key facebooktwittergooglegithub depending on the providers your application requires. For example:

'github' => [
    'client_id' => env('GH_ID'),
    'client_secret' => env('GH_SECRET'),
    'redirect' => env('APP_URL') . '/oauth/github/callback',
],

And open your .env file and paste  client_id and client_secret for each providers.

GH_ID=your-github-app-id
GH_SECRET=your-github-app-secret

You can obtain credentials by visiting following developer areas to setup all the providers in services.

Note : Make sure to set

APP_URL=http://localhost:8000

in .env file and it must match the providers redirect URL. Later in production you can change this to your actual app url. 

Visit providers website dev section and create Developer applications then fill the below details for each providers in config/services.php. For Github , you have to visit

 https://github.com/settings/developers

 and after visiting here fill this input field like below.

login-with-github

and after getting your client_id and client_secret , open .env file and paste  client_id and client_secret for each providers and fill the below details for each providers in config/services.php file.

config/services.php

'github' => [
    'client_id'     => env('GH_ID'),
    'client_secret' => env('GH_SECRET'),
    'redirect'      => env('APP_URL') . '/oauth/github/callback',
]

 For facebook client_id and client_secret , visit 

https://developers.facebook.com

 and add again in config/services.php file

config/services.php

'facebook' => [
    'client_id'     => env('FB_ID'),
    'client_secret' => env('FB_SECRET'),
    'redirect'      => env('APP_URL') . '/oauth/facebook/callback',
]

For twitter client_id and client_secret , visit 

https://apps.twitter.com

 and add again in config/services.php

config/services.php

'twitter' => [
    'client_id'     => env('TW_ID'),
    'client_secret' => env('TW_SECRET'),
    'redirect'      => env('APP_URL') . '/oauth/twitter/callback',
],

For twitter client_id and client_secret , visit 

https://console.developers.google.com

 and add again in config/services.php file

config/services.php

'google' => [
    'client_id'     => env('GL_ID'),
    'client_secret' => env('GL_SECRET'),
    'redirect'      => env('APP_URL') . '/oauth/google/callback',
],

To start just add Github first, if you can make one work rest will be very easy, you just need client_id and secret for all the providers you wanted to support in config/services.php configuration file.

Step 5 : Setup Route

We will need three routes, one for showing the list of buttons for providers, another for Redirect to the provider for authentication and last one to handle the callback from provider once authorized.

routes/web.php

Route::get('auth/social', 'Auth\[email protected]')->name('social.login');
Route::get('oauth/{driver}', 'Auth\[email protected]')->name('social.oauth');
Route::get('oauth/{driver}/callback', 'Auth\[email protected]')->name('social.callback');

Step 6 : Setup Controller

Now visit your app/Http/Controllers/Auth/LoginController and add this following code.

app/Http/Controllers/Auth/LoginController.php

namespace App\Http\Controllers\Auth;

use App\User;
use Exception;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;

class LoginController extends Controller
{

    public function __construct()
    {
        $this->middleware('guest');
    }

    protected $providers = [
        'github','facebook','google','twitter'
    ];

    public function show()
    {
        return view('auth.login');
    }

    public function redirectToProvider($driver)
    {
        if( ! $this->isProviderAllowed($driver) ) {
            return $this->sendFailedResponse("{$driver} is not currently supported");
        }

        try {
            return Socialite::driver($driver)->redirect();
        } catch (Exception $e) {
            // You should show something simple fail message
            return $this->sendFailedResponse($e->getMessage());
        }
    }

  
    public function handleProviderCallback( $driver )
    {
        try {
            $user = Socialite::driver($driver)->user();
        } catch (Exception $e) {
            return $this->sendFailedResponse($e->getMessage());
        }

        // check for email in returned user
        return empty( $user->email )
            ? $this->sendFailedResponse("No email id returned from {$driver} provider.")
            : $this->loginOrCreateAccount($user, $driver);
    }

    protected function sendSuccessResponse()
    {
        return redirect()->intended('home');
    }

    protected function sendFailedResponse($msg = null)
    {
        return redirect()->route('social.login')
            ->withErrors(['msg' => $msg ?: 'Unable to login, try with another provider to login.']);
    }

    protected function loginOrCreateAccount($providerUser, $driver)
    {
        // check for already has account
        $user = User::where('email', $providerUser->getEmail())->first();

        // if user already found
        if( $user ) {
            // update the avatar and provider that might have changed
            $user->update([
                'avatar' => $providerUser->avatar,
                'provider' => $driver,
                'provider_id' => $providerUser->id,
                'access_token' => $providerUser->token
            ]);
        } else {
            // create a new user
            $user = User::create([
                'name' => $providerUser->getName(),
                'email' => $providerUser->getEmail(),
                'avatar' => $providerUser->getAvatar(),
                'provider' => $driver,
                'provider_id' => $providerUser->getId(),
                'access_token' => $providerUser->token,
                // user can use reset password to create a password
                'password' => ''
            ]);
        }

        // login the user
        Auth::login($user, true);

        return $this->sendSuccessResponse();
    }

    private function isProviderAllowed($driver)
    {
        return in_array($driver, $this->providers) && config()->has("services.{$driver}");
    }
}

We know that many facebook user open their account using mobile number. So they have no email account in their facebook account.

So we can check a user if their facebook account contains a email or not, if not then we will force him to authenticate using another socialite services like github , google or twitter. So how can we do that, just see below code.

 protected function loginOrCreateAccount($providerUser, $driver) {

    // check for already has account
    $user = User::where('email', $providerUser->getEmail())->first();

// if user already found
        if( $user ) {
            // update the avatar and provider that might have changed
            $user->update([
                'avatar' => $providerUser->avatar,
                'provider' => $driver,
                'provider_id' => $providerUser->id,
                'access_token' => $providerUser->token
            ]);
        } else {
              if($providerUser->getEmail()){ //Check email exists or not. If exists create a new user
               $user = User::create([
                  'name' => $providerUser->getName(),
                  'email' => $providerUser->getEmail(),
                  'avatar' => $providerUser->getAvatar(),
                  'provider' => $driver,
                  'provider_id' => $providerUser->getId(),
                  'access_token' => $providerUser->token,
                  'password' => '' // user can use reset password to create a password
            ]);

             }else{
            
            //Show message here what you want to show
            
           }
      }

      // login the user
        Auth::login($user, true);
        return $this->sendSuccessResponse();
  }

Now lets create the view for login screen.

Step 7 : Create Blade File

Create our blade file to show login button. To create login button for corresponding socialite system. Just paste this below code to you resources/views/auth/login.php file.

Read more : Captcha Code and Validation Example using Botdetect Package in Laravel

resources/views/auth/login.php

Now visit this below url 

 http://localhost:8000/login

to check whether it works or not. Hope it can help you and it will work for your application. 

Codechief is a very fast growing community among programmers and have a reach of around 1 million+ readers globally. Contribution at Codechief is open for all those who have a passion to learn and help others by sharing their knowledge. If you think you have the zeal to learn, start contributing on Codechief contribute. you can also mail your article to [email protected] See your article appearing on the codechief main page and help other code.

We believe that everyone has the right to learn, so we allow both students and professionals to contribute on Codechief.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

A web enthusiastic, self-motivated Full-Stack Web Developer from Dhaka, Bangladesh with experience in developing applications using JavaScript, Laravel & Wordpress specifically. Facebook Github Website