Complete Laravel 5 Socialite tutorial

Adding social login is one of essential practice for any website these days, but adding each social provider can be hard and their constantly changing API makes it even harder to maintain, but socialite package in Laravel makes it easier, lets see how to use socialite to integrate authentication of all popular social sites.

Prerequisites

You must register your app with each provider you are going to add:

Facebook - check out Facebook app registration process

Google - check out Google project registration process

Github - check out GitHub app registration process

What we are going to build

In this tutorial, we are going to build a simple app which will contain Facebook, Github and Google login buttons to log in our web app.

Social Login App Demo

Getting Socialite package:

Assuming you have composer installed globally, Open terminal, navigate to your project root and run the following command - 

composer require laravel/socialite

Now open config/app.php and update providers array to use socialite package.

<?php
   
'providers' => [
 
      Laravel\Socialite\SocialiteServiceProvider::class

]

Let's also update aliases in config/app.php so we can use socialite package as façade.

<?php

'aliases' => [

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

]

Now open config/services.php and add your social login credentials, we will use env file to store our credentials.

<?php 

return [

    /** other code **/


    /** add code here **/

   'github' => [
        'client_id' =>  env('GITHUB_CLIENT_ID'),
        'client_secret' => env('GITHUB_CLIENT_SECRET'),
        'redirect' => env('GITHUB_REDIRECT'),
    ],
    'facebook' => [
        'client_id' =>  env('FACEBOOK_APP_ID'),
        'client_secret' => env('FACEBOOK_APP_SECRET'),
        'redirect' => env('FACEBOOK_REDIRECT'),
    ],
    'google' => [
        'client_id' =>  env('GOOGLE_APP_ID'),
        'client_secret' => env('GOOGLE_APP_SECRET'),
        'redirect' => env('GOOGLE_REDIRECT'),
    ]
]

Setting up required Routes

We don't want to add additional routes for every provider we add so we need some kind of URL pattern which allows use to use as few routes as possible.

We are going to add two routes for authentication, one route will send our login request to the social site and another route will handle redirect back request from social sites after their authentication process is done.

We will also create a route for home, the user will be redirected to this route after successful authentication.

<?php

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

Route::get('social/login/redirect/{provider}', ['uses' => 'Auth\AuthController@redirectToProvider', 'as' => 'social.login']);
Route::get('social/login/{provider}', 'Auth\AuthController@handleProviderCallback');

social/login/{provider} will invoke redirectToProvider method which is going to redirect to given provider for authentication.

social/login/callback/{provider} calls handleProviderCallback method, this method will handle data that is returned from social site and will login user to our site.

Creating Views

We have two views social.blade.php contains login buttons for social sites, and we have a home view( home.blade.php) where we will be redirected after a successful login attempt.

Let's start with master page:

resources/views/master.blade.php

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="_token" content="{{ csrf_token() }}"/>
    <title>Social Login</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            padding-top : 70px;
        }
    </style>
</head>
<body>
    <div class="container">
        @yield('content')
    </div>

    <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
</body>
</html>

resources/views/auth/Social.blade.php

@extends('master')

@section('content')
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
        	<h2>Login Using Social Sites</h2>
            <a class="btn btn-primary" href="{{ route('social.login', ['github']) }}">Github</a>
            <a class="btn btn-primary" href="{{ route('social.login', ['facebook']) }}">Facebook</a>
            <a class="btn btn-primary" href="{{ route('social.login', ['google']) }}">Google</a>
        </div>
    </div>
@stop

resources/views/home.blade.php

@extends('master')

@section('content')
	<h1>Hello {{ Auth::user()->name }}</h1>
@stop

 

Modify our app/Http/Controllers/Auth/AuthController.php to work with social logins

Now we need to create redirectToProvider and handleProviderCallback method. handleProviderCallback method will handle the data returned from social site so once users are authenticated to social site and returns to our site, we need to log them in, to do so, we need to store user credentials to our User table, we will use user model to accomplish this task.

<?php

namespace App\Http\Controllers\Auth;

use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;


//Add These three required namespace

use Laravel\Socialite\Facades\Socialite;
use Illuminate\Support\Facades\Auth;
use App\User;

class AuthController extends Controller
{
 
    use AuthenticatesAndRegistersUsers, ThrottlesLogins;

    public function __construct()
    {
        $this->redirectPath = route('home');
    }

    public function redirectToProvider($provider)
    {
        return Socialite::driver($provider)->redirect();
    }
    
     public function handleProviderCallback($provider)
    {
     //notice we are not doing any validation, you should do it

        $user = Socialite::driver($provider)->user();
         
        // stroing data to our use table and logging them in
        $data = [
            'name' => $user->getName(),
            'email' => $user->getEmail()
        ];
     
        Auth::login(User::firstOrCreate($data));

        //after login redirecting to home page
        return redirect($this->redirectPath());
    }
}

That's it guys, now you can log the user in using socialite package, this package comes with numbers of social providers but if you want to add more providers, you should check out socialite providers package.

If you are getting any error, check if you have added Illuminate\Support\Facades\Auth and  Laravel\Socialite\Facades\Socialite and if you still have a problem, feel free to ask us in the comment section or create the new thread in our forum.

Something to say? Tell us in comment section.