Social Login System Using Laravel Socialite

Credit: This article is inspired by this post Laravel Social Authentication with Socialite

Are you looking to implement social login system in your Laravel website? By allowing social login, your users don’t need to register on your website. It also saves us a lot of work like sending activation links and verifying email accounts. In this article, we study how to add social login system using Laravel Socialite.

Laravel Socialite library provides OAuth authentication with Facebook, Twitter, Google, LinkedIn, GitHub, and Bitbucket. What we need to do is install this library in our Laravel website, configure it, and get API keys from a social site and we are good to go.

Social Login Links

Create Users Table

For implementing social login system, we need to create users table which will store the details provided by the social site.

If you have a fresh installation of Laravel, open the command-line tool in the root directory of a project and run the command php artisan make:auth. This command will create authentication controllers like LoginController, RegisterController, etc. which are located in the app/Http/Controllers/Auth directory. It also creates a views login.blade.php, register.blade.php under the resources/view/auth directory.

Next, open the migration for users table. We will modify this default migration and add two more columns called provider and provider_id.

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->nullable();
        $table->string('password')->nullable();
        $table->string('provider');
        $table->string('provider_id');
        $table->rememberToken();
        $table->timestamps();
    });
}

As you see we set email and password columns to nullable. Why? When we use social login authentication there is no guarantee of getting an email id of a user. And the password is also not necessary in such cases. So we keep the email and password nullable. The column provider will store social site names like facebook, twitter, etc. Column provider_id will store the social id of a user respective to the social site.

Once you modified your user migration as above run the command php artisan migrate. It will create a table called ‘users’ in your database.

Probably, while running the migration command you will get some strange error related to character length. If so, then open the file AppServiceProvider.php file from the app/Providers directory. In this file, we need to set the default string length for database table columns.

File AppServiceProvider.php

<?php
 
namespace App\Providers;
 
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;
 
class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Schema::defaultStringLength(255);
    }
 
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

User Model

By default, Laravel includes an App\User Eloquent model in your app directory. Open the User.php from the app folder. Add two more columns provider, provider_id to the $fillable variable.

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

Install And Configure Laravel Socialite

To install this library, you should have Composer installed on your system.

In your command-line tool run the below command.

composer require laravel/socialite

After installing the library, register Laravel\Socialite\SocialiteServiceProvider in your config/app.php configuration file.

'providers' => [
    // Other service providers...
 
    Laravel\Socialite\SocialiteServiceProvider::class,
],

In the same file config/app.php, under the aliases array, add the Socialite facade.

'Socialite' => Laravel\Socialite\Facades\Socialite::class,

Now, it’s time to register your application on social sites. For instance, we assume you want to implement Facebook login authentication. So go ahead and create an application on Facebook.

Once, you are ready with the app id, and app secret of your Facebook application, open the file config/services.php and add the below code to it.

'facebook' => [
    'client_id' => env('FB_APP_ID'),
    'client_secret' => env('FB_APP_SECRET'),
    'redirect' => env('FB_CALLBACK_URL'),
],

As shown in the above code, we have to store our application details and callback URL in the .env file.

FB_APP_ID=PASTE_APP_ID_HERE
FB_APP_SECRET=PASTE_APP_SECRET_HERE
FB_CALLBACK_URL=YOU_SITE_URL/login/facebook/callback

We have passed the callback URL as YOU_SITE_URL/login/facebook/callback. Now, it’s time to create two routes, one for redirecting the user to the OAuth(In our case, Facebook) provider and another for receiving the callback from the provider after authentication.

Actual Code For Handling OAuth

At this stage, we are completed with all setups for Laravel Socialite. It’s time to write some code that handles redirection OAuth and fetches user details.

Open your login.blade.php file and place the below code in it probably after the submit button.

<div class="form-group">
    <div class="col-md-6 col-md-offset-4">
        Login with
        <a href="{{ url('/login/facebook') }}"><i class="fa fa-facebook-official" aria-hidden="true"></i> Facebook</a>
        <a href="{{ url('/login/twitter') }}"><i class="fa fa-twitter" aria-hidden="true"></i> Twitter</a>
        <a href="{{ url('/login/github') }}"><i class="fa fa-github" aria-hidden="true"></i> Github</a>
    </div>
</div>

Here, we are adding a link for GitHub and Twitter. The steps for adding OAuth for these social sites are also the same as Facebook. You just need to create an application for respective social sites and store those details in the same way as we added for Facebook.

In your route file, define the routes as below.

Route::get('login/{provider}', 'Auth\LoginController@redirectToProvider');
Route::get('login/{provider}/callback', 'Auth\LoginController@handleProviderCallback');

Next, navigate to app/Http/Controllers/Auth/LoginController.php and modify the file. You should add the below code to it.

<?php
 
namespace App\Http\Controllers\Auth;
 
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Socialite;
use App\User;
use Auth;
 
class LoginController extends Controller
{
    /**
     * Redirect the user to the GitHub authentication page.
     *
     * @return Response
     */
    public function redirectToProvider($provider)
    {
        return Socialite::driver($provider)->scopes(['email'])->redirect();
    }
 
    /**
     * Obtain the user information from GitHub.
     *
     * @return Response
     */
    public function handleProviderCallback($provider)
    {
        $user = Socialite::driver($provider)->user();
        $authUser = $this->findOrCreateUser($user, $provider);
        Auth::login($authUser, true);
        return redirect($this->redirectTo);
    }
 
    /**
     * If a user has registered before using social auth, return the user
     * else, create a new user object.
     * @param  $user Socialite user object
     * @param $provider Social auth provider
     * @return  User
     */
    public function findOrCreateUser($user, $provider)
    {
        $authUser = User::where('provider_id', $user->id)->first();
        if ($authUser) {
            return $authUser;
        }
        return User::create([
            'name'     => $user->name,
            'email'    => $user->email,
            'provider' => $provider,
            'provider_id' => $user->id
        ]);
    }
}

The method redirectToProvider redirect the user to the login page of a social site. Once the user authorizes the application, we fetch user information in the function handleProviderCallback. If the user does not exist with our system then we add their details using the method findOrCreateUser.

We hope you got to know about the social login system using Laravel Socialite. If you have any questions or suggestions please leave a comment below.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *