Laravel social login with Socialite package

  1 year ago     Views:  804  
Site Admin
4 Follows


Laravel is currently most popular web application framework written in PHP. Laravel provides many features which makes it popular framework. Laravel also provides built-in support for user login and register. In addition to default authentication, Laravel also provides login with social accounts using Laravel Socialite. Currently Socialite provides login with Google, Facebook, Twitter, LinkedIn, Github, Gitlab and BitBucket.

Prerequisites

We assume you have fresh Laravel application and also enabled Login or else you can enable auth by bellow command.

php artisan make:auth

You also need to have Composer installed, that make easy to manage packages from Packagist.

In this tutorial we will create Login with Google and Facebook using Laravel Socialite provided by Laravel. Follow these steps to install and configure social login in your Laravel application.

Step 1. Install package

Open Terminal and run following command from the root of Laravel application.

composer require laravel/socialite

Step 2. Register service provider

If you have Laravel 5.4 or lower, open config/app.php file and register Service provider by adding this line in providers array.

'providers' => [
    ...

    // Package Service Providers...
    Laravel\Socialite\SocialiteServiceProvider::class,
],

Add this line in aliases array to setup alias.

'aliases' => [
    ...

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

Step 3. Add Social account credentials.

After that, go to config/services.php file and add credentials for account whichever you want to include.

We will add Google and Facebook credentials here. You can put credentials direct here or load from .env file.

'facebook' => [
    'client_id' => env('FACEBOOK_CLIENT_ID'),
    'client_secret' => env('FACEBOOK_CLIENT_SECRET'),
    'redirect' => env('FACEBOOK_REDIRECT_URL'),
],

'google' => [
    'client_id' => env('GOOGLE_CLIENT_ID'),
    'client_secret' => env('GOOGLE_CLIENT_SECRET'),
    'redirect' => env('GOOGLE_REDIRECT_URL'),
    'auth_url' => env('GOOGLE_AUTH_URL'),
],

For Facebook credentials, go to https://developers.facebook.com and create developer account. You also need to create app for and get credentials here.

For Google credentials, go to https://console.developers.google.com and create project. You need to enable "Google+ API" at https://console.developers.google.com/apis/library.

In the Credentials tab, you can create and set credentials. You can also check this guide to Setup Google Developer account.

Step 4. Create routes

In the routes/web.php add the following lines to create login routes.

Route::get('login/{provider}', 'Auth\LoginController@redirectToProvider')->name('socialLogin.redirect');
Route::get('login/{provider}/callback', 'Auth\LoginController@handleProviderCallback')->name('socialLogin.callback');

Step 5. Add logic in LoginController

Find the App/Http/Controllers/Auth/LoginController.php and add these methods.

<?php

namespace App\Http\Controllers\Auth;

use Auth;
use Socialite;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class LoginController extends Controller
{
    /**
     * Redirect the user to the social authentication page.
     *
     * @return \Illuminate\Http\Response
     */
    public function redirectToProvider($provider)
    {
        return Socialite::driver($provider)->redirect();
    }

    /**
     * Obtain the user information from social.
     *
     * @return \Illuminate\Http\Response
     */
    public function handleProviderCallback(Request $request, $provider)
    {
        $user = Socialite::driver($provider)->user();

        $auth_user = $this->findOrCreateUser($user, $provider);

        Auth::login($auth_user, true);
    }

    /**
     * get or create user.
     *
     * @return \Illuminate\Http\Response
     */
    public function findOrCreateUser($user, $provider)
    {
        $authUser = User::where('email', $user->email)->first();

        if ($authUser) {
            return $authUser;
        }

        $name = explode(' ', $user->name);

        return User::create([
            'first_name' => $name[0],
            'last_name' => isset($name[1]) ? $name[1] : ''
            'email' => $user->email,
            'provider' => $provider,
            'provider_id' => $user->id,
            'avatar' => $user->avatar
        ]);
    }
}

The first method redirectToProvider($provider) will redirect to user to Social login page. You need to pass $provider parameter as OAuth provider that you defined in config/services.php. Add this href in your Social login buttons.

<a href="{{ route('socialLogin.redirect', 'facebook') }}">Login with Facebook</a>
<a href="{{ route('socialLogin.redirect', 'google') }}">Login with Google</a>

After the successfully redirect, the user will be redirect back to the handleProviderCallback() method, where you can get $user variable as defined in the method. Now with $user details, you can create new user and save to database or direct login user if already exists with calling findOrCreateUser() method.

Conclusion

In that way, you can also add more social logins as defined above. For more login option Go to Official Documentation. There are more options that may suits most your project.


Was this article helpful?

1 out of 1 person found this article helpful.

Leave a comment

OR

1 Comments

  • Image
    LeoSilver
    December 23, 2019 Reply

    Hi, all these plugins use the services.php file to configure the credentials client_id etc, but noen of them allow for dynamic credentials pulled from database. How could this be used?

    Image
    Jitesh Meniya
    Thu December, 2019

    Hi LeoSilver,

    Thank you. Merry Christmas and Happy new year...

    You can overwrite config value runtime to controller by calling Config::set() method. First get data from database, i.e., $database_credentials and then set its value in the __construct() method of LoginController. This way, you can use database variable to login.
    Config::set('services.facebook', $database_credentials);

    Other way is directly use database query in config/services.php file and assign value to 'facebook' array.