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 lot of work like sending activation link, verifies email account. 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, 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 a 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 app/Http/Controllers/Auth directory. It also creates a views login.blade.php, register.blade.php under 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 case. So we keep email and password to nullable. The column provider will store social site name 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 app/Providers directory. In this file, we need to set default string length for a 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 Socialite facade.

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

Now, it’s time to register your application on social site. 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 app id, app secret of your Facebook application, open the file config/services.php and add 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 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 setup for Laravel Socialite. It’s time to write some code which handles redirection OAuth and fetch 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 also same as Facebook. You just need to create an application of 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 in 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 user to login page of a social site. Once user authorize 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 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 *