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.







GitHub Login With PHP Laravel Socialite | StackCoder


GitHub Login With PHP Laravel Socialite


Share On     Share On WhatsApp     Share On LinkedIn


Hello fellas! In this article, we will implement GitHub login with PHP Laravel Socialite package. This package is really awesome for all social logins.


We will cover the following


  1. Laravel Installation
  2. Socialite Package Downloading
  3. Using GitHub Account To Get OAuth For Code
  4. Database Users Table Setup
  5. Setting Up OAuth Details For Laravel Socialite
  6. Route Setup For GitHub Socialite
  7. Controller Code For Calling GitHub Website
  8. Controller Code For Callback From GitHub
I have also written an article on Google, Twitter, GitHub, Facebook & Many Other Social Generic Logins With PHP Laravel Socialite

Step 1 - Laravel Installation


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 about the composer then I have written an article on it @ What Is Composer? How Does It Work? Useful Composer Commands And Usage


Step 2 - Socialite Package Downloading


For working with any social login we are having a cool official package from Laravel ie Socialite. Let's integrate it on our project using composer with the following command


composer require laravel/socialite

Step 3 - Using GitHub Account To Get OAuth For Code


1) Account Login - Please log in to your GitHub account.


2) Settings - On right top corner click on your Profile and in the dropdown list click on Settings link as shown in the following image


GitHub Settings

GitHub Settings


3) Developer Settings - Once you click on the settings you will be able to see the following page. Now click on Developer Settings as shown in the following image.


GitHub Developer Settings

GitHub Developer Settings


4) OAuth Registration Page - On click of the above page you be able to see 1) OAuth Apps on the left sidebar on click of that you can 2) Register New Application on the right panel as shown in the following


Register New OAuth Application

Register New OAuth Application


5) OAuth Form Filling - While filling the OAuth form keep the following things in your mind

i) Homepage URL - Make sure to add your web application URL. Since I will run locally I am adding it as http://localhost:8888

ii) Authorization Callback URL - This is the URL which GitHub will redirect after successful authentication of the user


iii) Click on the register application and submit the details.


OAuth Application Form

OAuth Application Form


6) OAuth Credentials - Once you click on register application GitHub will validate your form and redirect to OAuth Credentials page where you will be able to get the GitHub Client ID & GitHub Client Secret

GitHub Client ID & GitHub Client Secret

GitHub Client ID & GitHub Client Secret


Step 4 - Database Setup For Users


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


Users Migration

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 it. Please observe that I have nulled basically most of the fields.


Step 5 - Setting Up OAuth Details For Laravel Socialite


Let's configure the GitHub OAuth credentials in our Laravel application as follows


services.php (config/services.php)

'github' => [
        'client_id' => env('GITHUB_CLIENT_ID'),
        'client_secret' => env('GITHUB_CLIENT_SECRET'),
        'redirect' => env('GITHUB_CALLBACK_URL'),
],


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


.env

# GitHub OAuth
GITHUB_CLIENT_ID=2b144e2d5438d663834f
GITHUB_CLIENT_SECRET=55214f954c5029097cfba553320be91d01eb5e40
GITHUB_CALLBACK_URL=http://localhost:8888/auth/github/callback

Step 6 - Web Route Setup For GitHub Socialite


Now we have done all the configurations parts lets get to the coding part.


First, let's create the routes for our application inside web.php file as follows


web.php

Route::get('/auth/github', 'AuthController@socialProvider');
Route::get('/auth/github/callback', 'AuthController@socialProviderCallback');


AuthController@socialProvider [/auth/github] - This route method will decide which social web application it needs to redirect


AuthController@socialProviderCallback [/auth/github/callback]- This route method will be the one that will be called back after the authentication is successful from GitHub and we will see how to register the user.


Step 7 - Controller Code For Calling GitHub Website


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


AuthController -> socialProvider() [App / Http / Controllers / AuthController]

public function socialProvider()
{
  return Socialite::driver('github')->redirect();
}


Note: The driver's name must be same as that the of services key name.


When you run the application in website with the following URL, it will take to GitHub verification page


http://localhost:8888/auth/github


Authentication Page

Authentication Page


Step 8 - Controller Code For Callback From GitHub


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.


AuthController -> socialProviderCallback() [App / Http / Controllers / AuthController]

public function socialProviderCallback()
{
    /** 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('github')->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 no user found with that email then you can insert into database */
        if (!$user) {
            /** Create new user with GitHub credentials */
            $newUser = User::create([
                'provider_type'     => 'github',
                '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 of your database */
        if ($user->provider_type != 'github') {
            session()->flash('error', 'Please try logging with GitHub');
            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 code details with comments hope it helps you.


Conclusion


Hope you enjoyed the article. Please share with your friends.




Author Image
AUTHOR

Channaveer Hakari

I am a full-stack developer working at WifiDabba India Pvt Ltd. I started this blog so that I can share my knowledge and enhance my skills with constant learning.

Never stop learning. If you stop learning, you stop growing