using JavaScript OAuth Library – Coding Birds Online

using JavaScript OAuth Library – Coding Birds Online | ninjasquad

Hello everyone, Today in this tutorial I will show you how to create login with Google account using JavaScript OAuth-library in your web application. You can find N number of tutorials on Google authentication but this tutorial is different from them.

This tutorial tells how easy it is to integrate login with Google authentication. In this tutorial, you don’t need to use/download a third partly PHP library provided by Google, unlike other tutorials.

Instead of this you just need to register your app to Google API Console, generate the client Id and secret keys and include a CDN. Don’t worry I will cover each and every step and provide the source code.

Why use Login with Google OAuth library?

Login with Google, JavaScript OAuth library is a quick and powerful way to integrate the login system in the web application. If you do it by using JavaScript, It will enhance the user experience, without page refresh. Google login with JavaScript API allows the user to log in on your website with their Google account.

The best advantage of using the Google JavaScript API library is that the login process can be implemented on a single page without page refresh.  Check our demo.

Step by step process to Login with Google account

1- Create a project

To create a project click on this link you will get something like this.


Click on the Configure a project button and a popup window appears on the same page with a select dropdown. If you created any project that will be listed, If you didn’t create, click on create project option. Enter a project name and click next. You will get another window as.


In this first dropdown select “Web browser” and in the Authorized Javascript Origin, enter your URL or domain.


Click on Create, you will be asked to enter product name or application. This is the name shown during authentication.

Now you will get the Client ID and secret ID.


2- Enable API for the project

Open Google Developer Consol, on the top left you will get a dropdown. Select the project that you created in step 1.


Click on the +ENABLE APIS AND SERVICES button and you will be redirected to a page of API. Find Google+ API and enable it.


That’s it !!! Now we are just away from our dream. We need some code to configure. In this example, I have a Google Login button. When the user clicks on that, authenticated by his Google account. We save that information provided, for reference. And if he performs the same thing again then we just update our database.

  • config.php is the connection file to the database.
  • Google-auth-script.js is the JavaScript file to authenticate and saving the data by AJAX.
  • index.php is the main file that has the Google Login button.
  • loader-icon.gif is the loader icon.
  • script.php is the PHP script file that saves data to the database.

Let’s create these files.

   <link rel="stylesheet" href="">
<script src="" async defer></script>
    <meta name="google-signin-client_id" content="your_client_id">

Here, make sure you include Bootstrap and jQuery also. Since we will make AJAX request to save information. Include this above code to the head tag of the index.php file.

Learn more about how to make an AJAX request.

And Include this code to the footer of your index.php file, which means before closing to the body tag.

  <script src=""></script>
<script src=""></script>

index.php: paste this code to the body.

<div class="row">
            <div class="col-lg-8 posts-list">
                <div class="card card-signin my-5">
                    <div class="card-body">
                        <center><img src="" width="70"></center>
                        <h5 class="card-title text-center">Login with Google using JavaScript OAuth Library</h5>
                        <center><div id="g-signin2"></div></center>
                        <center><img src="" id="loaderIcon" style="display: none"></center>
                            <div class="card" style="width: 22rem;display: none" id="loginDetails">
                                <img class="" src="" width="100" id="profileLabel" style="margin-top: 20px;">
                                <div class="card-body">
                                    <div class="card-text" style="text-align: justify">
                                            <tr><td>Name</td><td>:</td><td id="nameLabel"></td></tr>
                                            <tr><td>Email</td><td>:</td><td id="emailLabel"></td></tr>
                                            <tr><td>Google ID</td><td>:</td><td id="googleIdLabel"></td></tr>
                                    <a href="" onclick="signOut();" class="btn btn-danger">Logout</a>


function renderButton() {
    gapi.signin2.render('g-signin2', {
        'scope': 'profile email',
        'width': 250,
        'height': 40,
        'longtitle': true,
        'theme': 'dark',
        'onsuccess': onSignIn,
        'onfailure': onFailure

function onSignIn(googleUser) {

    var profile = googleUser.getBasicProfile();

    console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
    console.log('Name: ' + profile.getName());
    console.log('Image URL: ' + profile.getImageUrl());
    console.log('Email: ' + profile.getEmail());

    var googleTockenId = profile.getId();
    var name = profile.getName();
    var email = profile.getEmail();
    var profile = profile.getImageUrl();


    saveUserData(googleTockenId,name,email,profile); // save data to our database for reference

// Sign-in failure callback
function onFailure(error) {

// Sign out the user
function signOut() {
    if(confirm("Are you sure to signout?")){
        var auth2 = gapi.auth2.getAuthInstance();
        auth2.signOut().then(function () {


function saveUserData(googleTockenId,name,email,profile) {
        function (response) {
        var data = response.split('^');
        if (data[1] == "loggedIn"){



By default after page load this function renderButton( ) is called automatically.


include "config.php";

if ($_POST['authProvider'] == "Google"){
    $authProvider = $_POST['authProvider'];
    $googleTockenId = $_POST['googleTockenId'];
    $name = $_POST['name'];
    $email = $_POST['email'];
    $profile = $_POST['profile'];
    $now = date('Y-m-d H:i:s');

    // Check whether the user data already exist in the database
    $queryCheck = "SELECT * FROM bird_google_auth WHERE authProvider="$authProvider" AND googleIdTocken = '$googleTockenId'";
    $resultCheck = $connection->query($queryCheck);
    if ($resultCheck->num_rows>0){
        $queryPerform = "UPDATE bird_google_auth SET authProvider="$authProvider",googleIdTocken = '$googleTockenId',name="$name",
        email="$email",profile="$profile",modified='$now' WHERE authProvider="$authProvider" AND googleIdTocken = '$googleTockenId'";
        $queryPerform = "INSERT INTO bird_google_auth SET authProvider="$authProvider", googleIdTocken = '$googleTockenId',name="$name",
        email="$email",profile="$profile",created='$now',modified='$now' ";

    $finalResultset = $connection->query($queryPerform) or die("Error in query".$connection->error);
        echo "test^loggedIn";


$connection = new mysqli("localhost","root","","codingbirds");
if (! $connection){
    die("Error in connection".$connection->connect_error);

3- Run the Code!

When you run the code and if everything is fine. You will get something like this. Don’t worry I will provide the 100% working source code. You only need to change the client ID only.


Source Code & Demo

You can download the full 100% working source code from here. You check this demo also.


I hope you learned explained above, If you have any suggestions, are appreciated. And if you have any errors comment here, I will help. You can download the full 100% working source code from here.

Ok, Thanks for reading this article, see you in the next post. If this code works for you, please leave a comment so that others can find code useful.

Happy Coding 🙂

Source: Internet

Leave a Comment

We are offering free coding tuts