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:
- Declare the functions.
- Authenticate on page load by checking timestamp in token file:
- If token is required, redirect user to Consent page and rewrite token file (in JSON).
- If token is not required, use access_token stored in file.
Complete the global variables at the beginning of the code specific to your app and the rest should work...
// 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; }
- // 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;
- }
Include the following at the end of all of this and to execute the functions but before any outputs (HTML or JS):
To view these or output to screen:
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):