Surfe.be - passive income

Laravel 5.8 : Facebook Login with Laravel Socialite

In this tutorial we learn about Laravel Socialite . In addition to typical, form based authentication, Laravel also provides a simple, convenient way to authenticate with OAuth providers using Laravel Socialite. Socialite currently supports authentication with Facebook, Twitter, LinkedIn, Google, GitHub, GitLab and Bitbucket. Laravel has simplified authentication processes either the traditional way or via social media like Facebook, Twitter, LinkedIn or Github by creating a Laravel Socialite Package. Let’s see how we can utilize this package for Facebook Authentication:

Installation

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

composer require laravel/socialite

Configuration

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.phpconfiguration file, and should use the key facebooktwitterlinkedingooglegithubgitlab or bitbucket, depending on the providers your application requires. 

Head over to your config/app.php and add the following in the providers array:

Laravel\Socialite\SocialiteServiceProvider::class

Still in your config/app.php file, also add this to the aliases array:

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

We just registered a Facade for Laravel Socialite.

Create Facebook app.

Head over to Facebook Developers Page . Under the My apps, there is a link to create a new app.A dialog box should appear afterwards showing you different options, Choose Website since we are building a web app. So give your app a name and click “Create new Facebook App ID”.I named mine “Laravel Auth”.Another dialog box should appear. Choose the Category. I chose “Education” for the purpose of this tutorial. Go ahead and create App ID. 

Head over to your config/services.php and add this:

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

Open your .env file and add your facebook client id, secret and callback url like so:

FACEBOOK_CLIENT_ID=xxxxxxxxx
FACEBOOK_CLIENT_SECRET=xxxxxxx
CALLBACK_URL=http://localhost:8000/auth/facebook/callback

where xxxxxxx refers to your APP ID and APP secret. You can find those details when you click on the name of your app in the dropdown that “My apps” provides on the facebook developer dashboard page.

Set up Routes and Controller Methods

You will need two routes: one for redirecting the user to the OAuth provider, and another for receiving the callback from the provider after authentication.

Add these to routes.php

Route::get('auth/facebook', 'Auth\AuthController@redirectToProvider');
Route::get('auth/facebook/callback', 'Auth\AuthController@handleProviderCallback');

Let’s Open up our AuthController.php file in Auth folder and add this:

    protected $redirectPath = '/home';
    /**
     * Redirect the user to the Facebook authentication page.
     *
     * @return Response
     */
    public function redirectToProvider()
    {
        return Socialite::driver('facebook')->redirect();
    }
    /**
     * Obtain the user information from Facebook.
     *
     * @return Response
     */
    public function handleProviderCallback()
    {
        try {
            $user = Socialite::driver('facebook')->user();
        } catch (Exception $e) {
            return redirect('auth/facebook');
        }
        $authUser = $this->findOrCreateUser($user);
        Auth::login($authUser, true);
        return redirect()->route('home');
    }
    /**
     * Return user if exists; create and return if doesn't
     *
     * @param $facebookUser
     * @return User
     */
    private function findOrCreateUser($facebookUser)
    {
        $authUser = User::where('facebook_id', $facebookUser->id)->first();
        if ($authUser){
            return $authUser;
        }
        return User::create([
            'name' => $facebookUser->name,
            'email' => $facebookUser->email,
            'facebook_id' => $facebookUser->id,
            'avatar' => $facebookUser->avatar
        ]);
    }

Note: Add the Socialite and Auth class reference at the top of this file like so:

use Auth;
use Socialite;

First, it redirects to Facebook, grabs the relevant information and then looks up the user and authenticate as that user. If the user doesn’t exist, it creates the user and authenticate.

Database

We need to update our users migration so that it will allow us to store facebook-specific information. Since this is a new app, I could just modify the users migration, but if you have an existing app, you’ll need to make a new migration.

 Model

Make those fields mass assignable in your User model. name, email, facebook_id and avatar like so:

 protected $fillable = ['name', 'email', 'facebook_id', 'avatar'];

Now let’s get to work.Head over to your welcome.php and edit it to have a login facebook button like so:Don’t forget to link the file with bootstrap.In your routes.php, add this:

Route::get('home', array('as' => 'home', 'uses' => function(){
  return view('home');
}));

Create home.blade.phpCopy the contents of welcome.blade.php into it and just update the body content to have this:Now, run your migrations lest we forget like so:

php artisan migrate

Are you ready to test your app?..after all the work! Now, run php artisan serve and click on the Login with Facebook button on your homepage . Yaaay!!!..Now we are logged in from facebook..and we can access our data from Facebook.Note: I drew heavy inspiration from Matt Stauffer’s blog post.So you can check how to use GitHub authentication for Login in Laravel 5 hereYou can decide to use the data for anything,…this tutorial aims to simply show you how to authenticate with facebook.You can find the full source code of this tutorial here . Please, if you have any questions or observations, let me know in the comments section!

Leave a comments

LET'S SOCIALITE

Recent Tweets

RECOMMENDED POST