Login with Github, Google, LinkedIn and Facebook in Laravel 6 Part 1
by Sam
Laravel has already provided login auth scaffolding. It is just easy to use or customize it. But sometimes, you would want to use other social media sites to do the authentication for you.
In this tutorial, I will help you create a social auth using these four social sites:
Github, Google, LinkedIn and Facebook
1. Install Laravel
Open your terminal and download the Laravel Framework by executing the command.
$ composer create-project --prefer-dist laravel/laravel mysocialite
It takes a few minutes to download. After that, go to mysocialite directory.
$ cd mysocialite
and then, start your server.
$ php artisan serve
Open your browser and go to http://localhost:8000
2. Configure your .env file
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=mysocialitedb
DB_USERNAME=root
DB_PASSWORD=
Make sure to change according to your host and database settings.
3. Customize User’s schema
Navigate to database » migrations » create_students_table.php and add additional fields
class CreateUsersTable extends Migration
{
...
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name')->nullable();
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password')->nullable();
$table->string('provider_name')->nullable();
$table->string('provider_id')->unique()->nullable();
$table->rememberToken();
$table->timestamps();
});
}
...
}
After adding of fields, migrate all to the database.
$ php artisan migrate
If error exists while migrating, please check this link.
From the schema above, notice that I added two important fields, provider_name and provider_id. The field provider_name will store the name of the provider we used in logging in while the provider_id is the unique id generated by the provider.
4. Assign fillable fields
class User extends Authenticatable
{
...
protected $fillable = [
'name', 'email', 'password', 'provider_name', 'provider_id'
];
}
5. Execute laravel authentication
$ composer require laravel/ui --dev
$php artisan ui vue --auth
The above commands were equivalent to php artisan make:auth
in laravel 5.8 and below. In laravel 6, make:auth
is no longer used. Please check the documentation for more details.
6. Configure Routing
Go to routes/web.php and add the codes below.
Route::get('login/{provider}', 'Auth\LoginController@redirectToProvider');
Route::get('login/{provider}/callback','Auth\LoginController@handleProviderCallback');
7. Add methods to LoginController
Let’s add methods into our LoginController.
// app\Http\Controllers\Auth\LoginController.php
...
Use App\Models\User;
use Auth;
use Socialite;
...
class LoginController extends Controller
{
...
public function redirectToProvider($provider)
{
return Socialite::driver($provider)->redirect();
}
public function handleProviderCallback($provider)
{
try {
$user = Socialite::driver($provider)->user();
} catch (Exception $e) {
return redirect('/login');
}
$authUser = $this->checkUser($user, $provider);
Auth::login($authUser, true);
return redirect($this->redirectTo);
}
public function checkUser($providerUser, $provider)
{
$account = User::where('provider_name', $provider)
->where('provider_id', $providerUser->getId())
->first();
if ($account) {
return $account->user;
} else {
$user = User::where('email', $providerUser->getEmail())
->first();
if (! $user) {
$user = User::create([
'email' => $providerUser->getEmail(),
'name' => $providerUser->getName(),
'provider_id' => $providerUser->getId(),
'provider_name' => $provider,
]);
}
return $user;
}
}
...
}
Notice that we passed provider from our route (Route::get('login/{provider}..)
) which will be handled by the handleProviderCallback($provider)
method. Then, it will call checkUser(..)
method to check validate data and create new record if it is not existing.
8. Modify login.blade.php
Let’s add social buttons. Copy the code below and paste it anywhere you want inside of login.blade.php
...
<a href="{{ url('login/github') }}" class="btn btn-primary">Login with Github</a>
<a href="{{ url('login/google') }}" class="btn btn-primary">Login with Google</a>
<a href="{{ url('login/facebook') }}" class="btn btn-primary">Login with Facebook</a>
<a href="{{ url('login/linkedin') }}" class="btn btn-primary">Login with LinkedIn</a>
...
9. Add provider providers into services.php
We’ll be needing necessary data from the providers later on, so, let’s prepare the services.
From your application project, go to config\services.php and add the following:
...
'github' => [
'client_id' => env('GITHUB_CLIENT_ID'),
'client_secret' => env('GITHUB_CLIENT_SECRET'),
'redirect' => env('GITHUB_CALLBACK_URL'),
],
'google' => [
'client_id' => env('GOOGLE_CLIENT_ID'),
'client_secret' => env('GOOGLE_CLIENT_SECRET'),
'redirect' => env('GOOGLE_CALLBACK_URL'),
],
'linkedin' => [
'client_id' => env('LINKEDIN_KEY'),
'client_secret' => env('LINKEDIN_SECRET'),
'redirect' => env('LINKEDIN_REDIRECT_URI')
],
'facebook' => [
'client_id' => env('FACEBOOK_KEY'),
'client_secret' => env('FACEBOOK_SECRET'),
'redirect' => env('FACEBOOK_REDIRECT_URI')
],
...
10. Configure .env
For security purposes, we have to put our data, generated by the providers, in our .env file. Let’s leave the CLIENT_ID and SECRET_ID be empty. We have to copy it later on.
...
GITHUB_CLIENT_ID=
GITHUB_CLIENT_SECRET=
GITHUB_CALLBACK_URL=http://localhost:8000/login/github/callback
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
GOOGLE_CALLBACK_URL=http://localhost:8000/login/google/callback
LINKEDIN_KEY=
LINKEDIN_SECRET=
LINKEDIN_REDIRECT_URI=http://localhost:8000/login/linkedin/callback
FACEBOOK_KEY=
FACEBOOK_SECRET=
FACEBOOK_REDIRECT_URI=http://localhost:8000/login/facebook/callback
11. Login using Github
11.1. Go to https://github.com/settings/developers page and login.
11.2. Go to Auth Apps
11.3. Click New OAuth App
11.4. Update your Application according to your configuration. You have to specify the domain URL(during production)or localhost for development. The callback URL is the URL we set in our routes above.
11.5. Copy the client ID and Secret ID.
and paste into your .env
...
GITHUB_CLIENT_ID=YOUR_CLIENT_ID
GITHUB_CLIENT_SECRET=YOUR_SECRET_ID
...
Then,
Try to test if it’s working.
Go to http://localhost:8000/login
and click the button Login using github.
To be continued…