PHP Web Application Authentication Using Google OAuth 2.0

This tutorial help to understand Google OAuth implementation with PHP. I will explain how PHP web applications use the Google API Client Library, and the implementation of OAuth 2.0 authorization to access Google APIs.

Google OAuth 2.0 allows users to share specific data with keeping their user names, passwords, and other information private. We will use Google OAuth Version 2.0 API.

Nowadays you can see many websites are using the google signin button to login users into the website without the registration process. Google OAuth API help to skip the tedious registration process and login into the website using Gmail id. Let’s start Google Oauth API with PHP.

Login with Google Account using PHP

We will let you know step by step process to register your app into Google api. Google provides the project secrets and key to the successful registration of the app.

Pre-Requisite

  • Register Web application with Google API Dashboard.
  • Download PHP Google API

We will use the following files and folder structure as follows:

  • index.php
  • google_oauth_config.php
    • vendor This folder has Google API, Google Client, Google Oauth and other libraries

You can also read other Google api Tutorials:

How to Register Project With Google Developer Console

  1. Go to the Google Developers Console and Sign-In with Google Gmail Id.
  2. Select an existing project from the projects drop-down or create a new project, For new project, We need to Enter the Project name and click Create to proceed.
  3. Select the newly created project into dropdown list and enable the Google+ API service.
  4. Select Library from the left sidebar, Now search the Google+ API service in the API list and select them and click enable.
  5. Select Credentials from sidebar, Click OAuth consent screen tab. Choose an Email address, enter the Product name and click save.
  6. Select the Credentials tab, click the Create credentials drop-down and select the OAuth client ID option.
  7. Now Application type section will be open, select the Web application option.
  8. Enter your app origin name in authorized JavaScript origins field, App redirect Url into Authorized redirect URIs files.
  9. Finally, Click the Create button
  10. A dialog box will be open with Client ID and Client secret. This Client ID and Client secret allows you to access the Google APIs.

Configure Google OAuth into PHP application

I have used composer to download php google api client, Its Very simple just goto project path and run below command:

composer require google/apiclient:^2.0
Above command will download all libs and stored into vendor folder.

We will open google_oauth_config.php file, We will define Google Project Client ID ($clientId), Client Secret ($clientSecret), and Callback URL ($redirectURL).

<?php
session_start();

//Google API PHP Library includes
require_once 'vendor/autoload.php';

// Set config params to acces Google API
 $client_id = 'XXXXXXX;
 $client_secret = 'XXXXXXXXX';
 $redirect_uri = 'https://phpflow.com/google-oauth-php';
 
//Create and Request to access Google API
$client = new Google_Client();
$client->setApplicationName("Google OAuth Login With PHP");
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);

$objRes = new Google_Service_Oauth2($client);

//Add access token to php session after successfully authenticate
if (isset($_GET['code'])) {
  $client-&gt;authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

//set token
if (isset($_SESSION['access_token']) &amp;&amp; $_SESSION['access_token']) {
  $client-&gt;setAccessToken($_SESSION['access_token']);
}

//store with user data
if ($client->getAccessToken()) {
  $userData = $objRes-&gt;userinfo-&gt;get();
  if(!empty($userData)) {
	//insert data into database
  }
  $_SESSION['access_token'] = $client-&gt;getAccessToken();
} else {
  $googleAuthUrl  =  $client-&gt;createAuthUrl();
}
?>

View File for Login and Display Information

We will use index.php file for the entry point of the application, The Google Sign button will be shown when the user will come to the web app, Once they authenticated with their Google account. PHP application will display user information with logout button. I am just showing success message but you can display information into page.

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
	<!-- jQuery -->
	<style type="text/css">
	body { margin-top:20px; }
	.panel-body:not(.two-col) { padding:0px }
	.glyphicon { margin-right:5px; }
	.glyphicon-new-window { margin-left:5px; }
	.panel-body .radio,.panel-body .checkbox {margin-top: 0px;margin-bottom: 0px;}
	.panel-body .list-group {margin-bottom: 0;}
	.margin-bottom-none { margin-bottom: 0; }
	.panel-body .radio label,.panel-body .checkbox label { display:block; }
	/* Shared */
.loginBtn {
  box-sizing: border-box;
  position: relative;
  /* width: 13em;  - apply for fixed size */
  margin: 0.2em;
  padding: 0 15px 0 46px;
  border: none;
  text-align: left;
  line-height: 34px;
  white-space: nowrap;
  border-radius: 0.2em;
  font-size: 16px;
  color: #FFF;
}
.loginBtn:before {
  content: "";
  box-sizing: border-box;
  position: absolute;
  top: 0;
  left: 0;
  width: 34px;
  height: 100%;
}
.loginBtn:focus {
  outline: none;
}
.loginBtn:active {
  box-shadow: inset 0 0 0 32px rgba(0,0,0,0.1);
}


/* Google */
.loginBtn--google {
  /*font-family: "Roboto", Roboto, arial, sans-serif;*/
  background: #DD4B39;
}
.loginBtn--google:before {
  border-right: #BB3F30 1px solid;
  background: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/14082/icon_google.png') 6px 6px no-repeat;
}
.loginBtn--google:hover,
.loginBtn--google:focus {
  background: #E74B37;
}
</style>
<?php
include_once('google_oauth_config.php');
?>



<div class="container">

<h2>PHP Google OAuth 2.0 Login</h2>


<div class="well">
		    <?php if (isset($googleAuthUrl)): ?>
			<form action="<?php echo $googleAuthUrl; ?>" method="post">
			<button type="submit" class="loginBtn loginBtn--google">
		  Login with Google
		</button>
		</form>
		    <?php else: ?>

<h3>Successfully! Authenticated</h3>

		    <?php endif ?>
</div>


</div>

Logout functionality with Google OAuth2

User can able to logout from web application, We will add below code into google_oauth_config.php file.

//Logout
if (isset($_REQUEST['logout'])) {
  unset($_SESSION['access_token']);
  $client->revokeToken();
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL)); //redirect user back to page
}

Leave a Reply

Your email address will not be published. Required fields are marked *