Good content takes time and effort to come up with.
Please consider supporting us by just disabling your AD BLOCKER and reloading this page again.
We will cover how to implement Google, Twitter, GitHub, Facebook & Many Other Social Generic Logins With PHP Laravel Socialite. This package is really awesome for all social logins.
We will cover the following
If you have already setup Laravel then skip to the next step. Let's install Laravel application with the composer.
composer create-project --prefer-dist laravel/laravel socialite_testing
If you would like to learn more on the composer have written an article on it @ What Is Composer? How Does It Work? Useful Composer Commands And Usage
For working with any social login we are having a cool official package from Laravel Socialite. Let's integrate it on our project using composer with the following command
composer require laravel/socialite
I have written other articles which cover how to get the OAuth Tokens step by step. Kindly check the articles in the following links
Facebook Login With PHP Laravel Socialite
GitHub Login With PHP Laravel Socialite
The above process remains standard and all you need to do is go and collect the OAuth keys.
Basically we need to store the Provider Type
and Provider Auth Token
in our database so that we can verify the user for later usage
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('provider_type')->nullable()->comment('Social Account Type');
$table->string('provider_token')->nullable()->comment('Social Account Token');
$table->string('name');
$table->string('password')->nullable();
$table->string('forgot_password')->nullable();
$table->string('email');
$table->string('phone')->nullable();
$table->boolean('is_blocked')->default(0);
$table->softDeletes();
$table->timestamps();
});
I haven't used the default authentication for personal preferences, but feel free to use. Please observe that I have nulled basically most of the fields.
To configure the GitHub, Google, Facebook, Twitter OAuth credentials we have to add the following code in services.php file as shown below
'facebook' => [
'client_id' => env('FACEBOOK_CLIENT_ID'),
'client_secret' => env('FACEBOOK_CLIENT_SECRET'),
'redirect' => env('FACEBOOK_CALLBACK_URL'),
],
'google' => [
'client_id' => env('GOOGLE_CLIENT_ID'),
'client_secret' => env('GOOGLE_CLIENT_SECRET'),
'redirect' => env('GOOGLE_CALLBACK_URL'),
],
'github' => [
'client_id' => env('GITHUB_CLIENT_ID'),
'client_secret' => env('GITHUB_CLIENT_SECRET'),
'redirect' => env('GITHUB_CALLBACK_URL'),
],
/** Add other socialite oauth provider details here */
Append to the end of the return []
array in services.php
Basically any socialite account needs 3 things in the configuration
i) OAuth Client ID
ii) OAuth Client Secret
iii) Redirect URL which will be used to redirect back to your website URL after successful authentication
As we must not store any credentials inside our code so we will put the credentials inside .env
file
# Facebook OAuth
FACEBOOK_CLIENT_ID=432902173384581
FACEBOOK_CLIENT_SECRET=a5d233f8fc8baa694ee10a3a34501e823
FACEBOOK_CALLBACK_URL=http://localhost:8888/auth/facebook/callback
# Google OAuth
GOOGLE_CLIENT_ID="2299ds744856-i46e59s6mr12elsvs9aklp2346gkd2emm.apps.googleusercontent.com"
GOOGLE_CLIENT_SECRET=TSdlyITc0FKMS123ddda215W
GOOGLE_CALLBACK_URL=http://yourdomain.in:8888/auth/google/callback
# GitHub OAuth
GITHUB_CLIENT_ID=4b144e2d2338d6638123
GITHUB_CLIENT_SECRET=67214f954c5029097ceja553320be91d01eb5e40
GITHUB_CALLBACK_URL=http://localhost:8000/auth/github/callback
#Add other socialite OAuth provider details here
Note: Add other socialite OAuth provider details in services.php & .env files
Now we have done all the configurations parts lets get to the coding part.
First lets create the routes for our application inside web.php
file as follows
/** Social Logins */
Route::get('/auth/{provider}', 'AuthController@socialProvider');
Route::get('/auth/{provider}/callback', 'AuthController@socialProviderCallback');
AuthController@socialProvider [/auth/{provider}] - This route method will decide which social web application it needs to redirect
AuthController@socialProviderCallback [/auth/{provider}/callback]- This route method will be the one that will be called back after the authentication is successful from Facebook and we will see how to register the user.
By using Laravel Socialite its breeze for developer's life as it will handle most of the part for us.
As we saw from routes that we are redirecting [AuthController@socialProvider] to AuthController's socialProvider method. The following is the implementation
public function socialProvider($provider)
{
/** Since we are taking $provider via URL we must validate it properly */
$this->validateServiceProviders($provider);
/** If the above validation is successful then redirect to the specific driver */
return Socialite::driver($provider)->redirect();
}
/** Validate social service providers */
public function validateServiceProviders($provider)
{
if (!in_array($provider, ['google', 'facebook', 'github'])) {
return redirect('/auth/login')->send();
}
}
Note: The driver's name must be same as that of the services key name.
When you run the application on website with the following URL, it will take to the Facebook verification page
http://localhost:8888/auth/facebook
Similar to the above you can use it for GitHub as follows
http://localhost:8888/auth/github
For Google
http://localhost:8888/auth/google
Now you will be redirected to Facebook/Google/GitHub login page if you have not logged in or authorized page in you have already logged in to it.
With Step 7 when you click on Authorize
button and if the authentication is successful then it will redirect back to [AuthController@socialProviderCallback] AuthControllers's socialProviderCallback method.
So now we need to implement how to handle once we get back the successful redirect. Let's implement it.
public function socialProviderCallback($provider)
{
/** Again validate the social provider so as to check if its in the allowed ones */
$this->validateServiceProviders($provider);
/** Using try catch because if any user directly hits the URL then
* it will throw exception
*/
try {
/** Use socialite to get the user details like token, name, email, profile pic
* as per your needs
*/
$socialUser = Socialite::driver($provider)->user();
$token = $socialUser->token;
$name = $socialUser->name;
$email = $socialUser->email;
/** Uncomment the following to check the details description of user details */
//echo '<pre>'; print_r($socialUser);exit;
/** Get the user details */
$user = User::where('email', $email)->first();
if (!$user) {
/** Create new user with appropriate social provider credentials */
$newUser = User::create([
'provider_type' => $provider,
'provider_token' => $token,
'name' => $name,
'email' => $email,
]);
/** User is valid and store his details in session and redirect to dashboard */
session()->put('user_details', $newUser);
return redirect('/user/dashboard')->send();
}
/** Check user with provider exists in your database */
if ($user->provider_type != $provider) {
$providerType = !empty($user->provider_type) ? $user->provider_type : ' email & password';
session()->flash('error', 'Please try logging in with ' . $providerType);
return redirect('/auth/login');
}
/** Every time after successful authentication we will update provider token of our database */
$user->provider_token = $token;
$user->save();
/** User is valid and store his details in session and redirect to dashboard */
session()->put('user_details', $user);
return redirect('/user/dashboard')->send();
} catch (\Exception $e) {
session()->flash('error', 'Oops error in validating you. Try again');
return redirect('/auth/login');
}
}
I have tried to explain most of the code details with comments hope it helps you.
Hope you enjoyed the article. Please share it with your friends.
Use Different PHP Versions In Ubuntu / Linux
Firebase Cloud Messaging (FCM) Browser Web Push Notifications Using Javascript And PHP
Free SSL Certificate In cPanel With ZeroSSL & Certbot
Make Laravel Controllers Slim By Skimming Form Validation Request
Simple Way To Create Resourceful API Controller In Laravel
Upload File From Frontend Server {GuzzleHttp} To REST API Server In PHP {Laravel}
NGINX Security Best Practices & Optimization
What Is Laravel Resourceful Controllers?
Testing Laravel Emails With MailHog
Setup AMP (Accelerated Mobile Pages) In PHP Laravel
Free SSL Certificate For CPanel
Relationship Table Data With Route Model Binding In Laravel
Move Uploaded Files From Local Computer Or Server To Amazon S3 Bucket In PHP
PHP Built-In Web Server & Testing Your Development Project In Mobile Without Any Software