skip to Main Content

I’m using the latest version of the Google API Client PHP SDK (v2.11) to request an OAuth2 access token.

While retrieving an access token, I can see that the expires_in value is missing from the response, which leads to a PHP error when calling isAccessTokenExpired() later on:

Step 1 – Retrieve an access and refresh token

...
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$_SESSION['refresh_token'] = $client->getRefreshToken();
var_dump($client->getAccessToken());
...

Result

array(1) { ["access_token"]=> string(163) "xxxxxxxxxxxxxxxxxxx" }

It seems that both the expires_in and created columns are missing from this answer.

Step 2 – Let’s check if the Access token has expired and needs to be refreshed

$client->setAccessToken($_SESSION['access_token']);
if ($client->isAccessTokenExpired())
{
    $client->refreshToken($_SESSION['refresh_token']);
    $_SESSION['access_token'] = $client->getAccessToken();
}

Result

Warning: Undefined array key "expires_in" in
/var/www/admin/vendor/google/apiclient/src/Client.php on line 554

2

Answers


  1. Chosen as BEST ANSWER

    My API response was missing expires_in due to retrieving the tokens twice in my redirect.php script (called after the user has been authenticated).

    As described here, the OAuth refresh token as well as expires_in value are provided to you only during the first authorization. Adding a consent prompt also helped to address this issue.

    If you are doing some testing and need to reset the authorization you gave, you can do it here: https://myaccount.google.com/permissions

    Here's the full script, which is now working:

    <?php
    
    include(__DIR__.'/vendor/autoload.php');
    
    $client = new Google_Client();
    $client->setAccessType('offline');
    $client->setClientId(GOOGLE_OAUTH_CLIENT_ID);
    $client->setClientSecret(GOOGLE_OAUTH_CLIENT_SECRET);
    $client->setRedirectUri(BASE_URL.'/redirect.php');
    $client->addScope('email');
    $client->addScope('profile');
    $client->setPrompt('consent');
    
    if (isset($_GET['code']) && !empty($_GET['code']))
    {
        $client->authenticate($_GET['code']);
        if ($client->getAccessToken())
        {
            $google_oauth = new Google_Service_Oauth2($client);
            $google_account_info = $google_oauth->userinfo->get();
    
            if (!isset($google_account_info->hd) || $google_account_info->hd != 'mydomain.com')
                die('This domain name has not been authorized.');
            else
            {
                $redirect_uri = BASE_URL.(isset($_GET['state']) ? $_GET['state'] : '/');
                $_SESSION['picture'] = $google_account_info->picture;
                $_SESSION['access_token'] = $client->getAccessToken();
                $_SESSION['refresh_token'] = $client->getRefreshToken();
                $_SESSION['token_expiration'] = time() + 3600;
    
                header('Location: '.filter_var($redirect_uri, FILTER_SANITIZE_URL));
                exit;
            }
        }
    }
    

    It includes a domain check (i.e. replace mydomain.com by your own domain) as well as a referrer callback (i.e. populate state on your login page with the referrer first).


  2. This is the code I use. The library should be handling this for you.

    Oauth2Callback.php

    require_once __DIR__ . '/vendor/autoload.php';
    require_once __DIR__ . '/Oauth2Authentication.php';
    
    // Start a session to persist credentials.
    session_start();
    
    // Handle authorization flow from the server.
    if (! isset($_GET['code'])) {
        $client = buildClient();
        $auth_url = $client->createAuthUrl();
        header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
    } else {
        $client = buildClient();
        $client->authenticate($_GET['code']); // Exchange the authencation code for a refresh token and access token.
        // Add access token and refresh token to seession.
        $_SESSION['access_token'] = $client->getAccessToken();
        $_SESSION['refresh_token'] = $client->getRefreshToken();    
        //Redirect back to main script
        $redirect_uri = str_replace("oauth2callback.php",$_SESSION['mainScript'],$client->getRedirectUri());    
        header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
    }
    
    ?>
    

    Oauth2Authentication.php

    require_once __DIR__ . '/vendor/autoload.php';
    /**
     * Gets the Google client refreshing auth if needed.
     * Documentation: https://developers.google.com/identity/protocols/OAuth2
     * Initializes a client object.
     * @return A google client object.
     */
    function getGoogleClient() {
        $client = getOauth2Client();
    
        // Refresh the token if it's expired.
        if ($client->isAccessTokenExpired()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
            file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
        }
    return $client;
    }
    
    /**
     * Builds the Google client object.
     * Documentation: https://developers.google.com/identity/protocols/OAuth2
     * Scopes will need to be changed depending upon the API's being accessed.
     * Example:  array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
     * List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
     * @return A google client object.
     */
    function buildClient(){
        
        $client = new Google_Client();
        $client->setAccessType("offline");        // offline access.  Will result in a refresh token
        $client->setIncludeGrantedScopes(true);   // incremental auth
        $client->setAuthConfig(__DIR__ . '/client_secrets.json');
        $client->addScope([YOUR SCOPES HERE]);
        $client->setRedirectUri(getRedirectUri());  
        return $client;
    }
    
    /**
     * Builds the redirect uri.
     * Documentation: https://developers.google.com/api-client-library/python/auth/installed-app#choosingredirecturi
     * Hostname and current server path are needed to redirect to oauth2callback.php
     * @return A redirect uri.
     */
    function getRedirectUri(){
    
        //Building Redirect URI
        $url = $_SERVER['REQUEST_URI'];                    //returns the current URL
        if(strrpos($url, '?') > 0)
            $url = substr($url, 0, strrpos($url, '?') );  // Removing any parameters.
        $folder = substr($url, 0, strrpos($url, '/') );   // Removeing current file.
        return (isset($_SERVER['HTTPS']) ? "https" : "http") . '://' . $_SERVER['HTTP_HOST'] . $folder. '/oauth2callback.php';
    }
    
    
    /**
     * Authenticating to Google using Oauth2
     * Documentation:  https://developers.google.com/identity/protocols/OAuth2
     * Returns a Google client with refresh token and access tokens set. 
     *  If not authencated then we will redirect to request authencation.
     * @return A google client object.
     */
    function getOauth2Client() {
        try {
            
            $client = buildClient();
            
            // Set the refresh token on the client. 
            if (isset($_SESSION['refresh_token']) && $_SESSION['refresh_token']) {
                $client->refreshToken($_SESSION['refresh_token']);
            }
            
            // If the user has already authorized this app then get an access token
            // else redirect to ask the user to authorize access to Google Analytics.
            if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
                
                // Set the access token on the client.
                $client->setAccessToken($_SESSION['access_token']);                 
                
                // Refresh the access token if it's expired.
                if ($client->isAccessTokenExpired()) {              
                    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
                    $client->setAccessToken($client->getAccessToken()); 
                    $_SESSION['access_token'] = $client->getAccessToken();              
                }           
                return $client; 
            } else {
                // We do not have access request access.
                header('Location: ' . filter_var( $client->getRedirectUri(), FILTER_SANITIZE_URL));
            }
        } catch (Exception $e) {
            print "An error occurred: " . $e->getMessage();
        }
    }
    ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search