Google Authentication - OAuth 2.0 using PHP/cURL

What?
This is an article which lists the functions necessary to process Google Authentication using OAuth2.0. These functions allow a script to simply be loaded and to either create a token file, or use the existing one as long as it hasn't expired.

Update 2019
This script requires a user to authenticate the google account. I have a newer article called Google Drive API v3 - OAuth2 using Service Account in PHP/JWT documenting a script which accesses a Google Drive using a Service Account (unattended).

Why?
This is a big cop-out as I simply took someone else's functions and upgraded them to use the mentioned token based authentication. I find myself going through the motion and designing on a per-app basis so I wanted a standard way of doing it and I'll update this article as I improve on the code.

How?
So the plan is:
  1. Declare the functions.
  2. Authenticate on page load by checking timestamp in token file:
    1. If token is required, redirect user to Consent page and rewrite token file (in JSON).
    2. If token is not required, use access_token stored in file.
It is assumed that you have already registered the app with the Google developers console along with the redirect URI being this script.

Complete the global variables at the beginning of the code specific to your app and the rest should work...
copyraw
// specific to this app
$CLIENT_ID = '<your_client_id>';   // expecting *.apps.googleusercontent.com
$CLIENT_SECRET = '<your_client_secret>';   // expecting alphanumeric string
$STORE_PATH = '<absolute_or_relative_path_to_token_file>';   // expecting *.json - needs to be writeable by system account
$SCOPES = array($GAPIS_AUTH . 'userinfo.email', $GAPIS_AUTH . 'userinfo.profile');  // add in your other scopes as needed

// generic
$GAPIS = 'https://www.googleapis.com/';
$GAPIS_AUTH = $GAPIS . 'auth/';
$GOAUTH = 'https://accounts.google.com/o/oauth2/';
$REDIRECT_URI = 'http' . ($_SERVER['SERVER_PORT'] == 80 ? '' : 's') . '://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME'];

// retrieve from credentials file
function getStoredCredentials($path) {
    $credentials = json_decode(file_get_contents($path), true);
    $expire_date = new DateTime();
    $current_time = new DateTime();
    $expire_date->setTimestamp($credentials['created']-300);
    $expire_date->add(new DateInterval('PT' . $credentials['expires_in'] . 'S'));
    if ($current_time->getTimestamp() >= $expire_date->getTimestamp()) {
        $credentials = null;
        unlink($path);
    }
    return $credentials;
}

// store new credentials in file
function storeCredentials($path, $credentials) {
    $credentials['created'] = (new DateTime())->getTimestamp(); file_put_contents($path, json_encode($credentials));
    return $credentials;
}

// get authorization code
function requestAuthCode() {
    global $GOAUTH, $CLIENT_ID, $REDIRECT_URI, $SCOPES;
    $url = sprintf($GOAUTH . 'auth?scope=%s&redirect_uri=%s&response_type=code&client_id=%s&approval_prompt=force&access_type=offline', urlencode(implode(' ', $SCOPES)), urlencode($REDIRECT_URI), urlencode($CLIENT_ID) );
    header('Location:' . $url);
}

// request access token
function requestAccessToken($access_code) {
    global $GAPIS, $CLIENT_ID, $CLIENT_SECRET, $REDIRECT_URI;
    $url = $GAPIS . 'oauth2/v4/token';
    $post_fields = 'code=' . $access_code . '&client_id=' . urlencode($CLIENT_ID) . '&client_secret=' . urlencode($CLIENT_SECRET) . '&redirect_uri=' . urlencode($REDIRECT_URI) . '&grant_type=authorization_code';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $response=curl_exec($ch);
    if ($response === false) {
        return curl_error($ch);
    } else {
        return json_decode($response, true);
    }
    curl_close($ch);
}

// get token (access or refresh)
function getAccessToken($credentials) {
    $expire_date = new DateTime();
    $expire_date->setTimestamp($credentials['created']);
    $expire_date->add(new DateInterval('PT' . $credentials['expires_in'] . 'S'));
    $current_time = new DateTime();
    if ($current_time->getTimestamp() >= $expire_date->getTimestamp())
        return $credentials['refresh_token'];
    else
        return $credentials['access_token'];
}

// manage tokens
function authenticate() {
    global $STORE_PATH;
    $credentials = (file_exists($STORE_PATH)) ? getStoredCredentials($STORE_PATH) : null;
    if (!(isset($_GET['code']) || isset($credentials))) requestAuthCode();
    if (!isset($credentials)) $credentials = requestAccessToken($_GET['code']);
    if (isset($credentials) && isset($credentials['access_token']) && !file_exists($STORE_PATH)) $credentials = storeCredentials($STORE_PATH, $credentials);
    return $credentials;
}
  1.  // specific to this app 
  2.  $CLIENT_ID = '<your_client_id>';   // expecting *.apps.googleusercontent.com 
  3.  $CLIENT_SECRET = '<your_client_secret>';   // expecting alphanumeric string 
  4.  $STORE_PATH = '<absolute_or_relative_path_to_token_file>';   // expecting *.json - needs to be writeable by system account 
  5.  $SCOPES = array($GAPIS_AUTH . 'userinfo.email', $GAPIS_AUTH . 'userinfo.profile');  // add in your other scopes as needed 
  6.   
  7.  // generic 
  8.  $GAPIS = 'https://www.googleapis.com/'
  9.  $GAPIS_AUTH = $GAPIS . 'auth/'
  10.  $GOAUTH = 'https://accounts.google.com/o/oauth2/'
  11.  $REDIRECT_URI = 'http' . ($_SERVER['SERVER_PORT'] == 80 ? '' : 's') . '://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME']
  12.   
  13.  // retrieve from credentials file 
  14.  function getStoredCredentials($path) { 
  15.      $credentials = json_decode(file_get_contents($path), true)
  16.      $expire_date = new DateTime()
  17.      $current_time = new DateTime()
  18.      $expire_date->setTimestamp($credentials['created']-300)
  19.      $expire_date->add(new DateInterval('PT' . $credentials['expires_in'] . 'S'))
  20.      if ($current_time->getTimestamp() >= $expire_date->getTimestamp()) { 
  21.          $credentials = null
  22.          unlink($path)
  23.      } 
  24.      return $credentials
  25.  } 
  26.   
  27.  // store new credentials in file 
  28.  function storeCredentials($path, $credentials) { 
  29.      $credentials['created'] = (new DateTime())->getTimestamp()file_put_contents($path, json_encode($credentials))
  30.      return $credentials
  31.  } 
  32.   
  33.  // get authorization code 
  34.  function requestAuthCode() { 
  35.      global $GOAUTH, $CLIENT_ID, $REDIRECT_URI, $SCOPES
  36.      $url = sprintf($GOAUTH . 'auth?scope=%s&redirect_uri=%s&response_type=code&client_id=%s&approval_prompt=force&access_type=offline', urlencode(implode(' ', $SCOPES)), urlencode($REDIRECT_URI), urlencode($CLIENT_ID) )
  37.      header('Location:' . $url)
  38.  } 
  39.   
  40.  // request access token 
  41.  function requestAccessToken($access_code) { 
  42.      global $GAPIS, $CLIENT_ID, $CLIENT_SECRET, $REDIRECT_URI
  43.      $url = $GAPIS . 'oauth2/v4/token'
  44.      $post_fields = 'code=' . $access_code . '&client_id=' . urlencode($CLIENT_ID) . '&client_secret=' . urlencode($CLIENT_SECRET) . '&redirect_uri=' . urlencode($REDIRECT_URI) . '&grant_type=authorization_code'
  45.      $ch = curl_init()
  46.      curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields)
  47.      curl_setopt($ch, CURLOPT_POST, true)
  48.      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1)
  49.      curl_setopt($ch, CURLOPT_URL, $url)
  50.      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false)
  51.      curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false)
  52.      $response=curl_exec($ch)
  53.      if ($response === false) { 
  54.          return curl_error($ch)
  55.      } else { 
  56.          return json_decode($response, true)
  57.      } 
  58.      curl_close($ch)
  59.  } 
  60.   
  61.  // get token (access or refresh) 
  62.  function getAccessToken($credentials) { 
  63.      $expire_date = new DateTime()
  64.      $expire_date->setTimestamp($credentials['created'])
  65.      $expire_date->add(new DateInterval('PT' . $credentials['expires_in'] . 'S'))
  66.      $current_time = new DateTime()
  67.      if ($current_time->getTimestamp() >= $expire_date->getTimestamp()) 
  68.          return $credentials['refresh_token']
  69.      else 
  70.          return $credentials['access_token']
  71.  } 
  72.   
  73.  // manage tokens 
  74.  function authenticate() { 
  75.      global $STORE_PATH
  76.      $credentials = (file_exists($STORE_PATH)) ? getStoredCredentials($STORE_PATH) : null
  77.      if (!(isset($_GET['code']) || isset($credentials))) requestAuthCode()
  78.      if (!isset($credentials)) $credentials = requestAccessToken($_GET['code'])
  79.      if (isset($credentials) && isset($credentials['access_token']) && !file_exists($STORE_PATH)) $credentials = storeCredentials($STORE_PATH, $credentials)
  80.      return $credentials
  81.  } 

Include the following at the end of all of this and to execute the functions but before any outputs (HTML or JS):
copyraw
$credentials = authenticate();
  1.  $credentials = authenticate()

To view these or output to screen:
copyraw
print_r($credentials);
  1.  print_r($credentials)

Worthwhile Note(s)
Allowing the scope to access the user profile also sends through a JSON Web Token (JWT) under the variable "id_token". This will be included in the response from the Google Authentication process and if you store the credentials in a file, then the JWT is also in the file. A JWT is a three part value delimited by a period/dot. Base64 decode the second part and this will reveal the user's name and email (along with other profile settings) which you will have to be careful on ensuring this is NOT passed back to the system or is retrievable by any third-party.

Source(s):
Category: Google :: Article: 651

Credit where Credit is Due:


Feel free to copy, redistribute and share this information. All that we ask is that you attribute credit and possibly even a link back to this website as it really helps in our search engine rankings.

Disclaimer: Please note that the information provided on this website is intended for informational purposes only and does not represent a warranty. The opinions expressed are those of the author only. We recommend testing any solutions in a development environment before implementing them in production. The articles are based on our good faith efforts and were current at the time of writing, reflecting our practical experience in a commercial setting.

Thank you for visiting and, as always, we hope this website was of some use to you!

Kind Regards,

Joel Lipman
www.joellipman.com

Related Articles

Joes Revolver Map

Joes Word Cloud

Accreditation

Badge - Certified Zoho Creator Associate
Badge - Certified Zoho Creator Associate

Donate & Support

If you like my content, and would like to support this sharing site, feel free to donate using a method below:

Paypal:
Donate to Joel Lipman via PayPal

Bitcoin:
Donate to Joel Lipman with Bitcoin bc1qf6elrdxc968h0k673l2djc9wrpazhqtxw8qqp4

Ethereum:
Donate to Joel Lipman with Ethereum 0xb038962F3809b425D661EF5D22294Cf45E02FebF
© 2024 Joel Lipman .com. All Rights Reserved.