Joaquim d'Souza
Joaquim d'Souza

Reputation: 1516

PHP Google API Client caching access token

I am developing a web app that fetches and displays google analytics data for users that are not technical enough to do this themselves.

To do this, I:

1) have users log in with OAuth

2) store the access token

3) create a Google_Client and give it this access token

4) use this Google_Client to fetch the analytics data

This works no problem for the first user. However, it fails with an 'Access Denied' response for the second user. Following through the PHP code, I discovered that this is because the Google API Client caches the original access token (in the file system at /var/tmp/google-api-php-client), and uses this one instead of the fresh access token I have provided.

How do I prevent the Google API Client from caching the access token in the file system?

(Background information on the cache the Google_Client is using: when you provide an access token, it stores this with a key derived from the token scope. As the scope remains the same when the access token changes, the Google_Client does not create a new cache entry for each access token.)

Upvotes: 3

Views: 3522

Answers (4)

Rafał Toboła
Rafał Toboła

Reputation: 376

For me:

$client = \Google_Client();
//...        
$client->getCache()->clear();
$client->setAccessToken($access_token);

worked perfectly.

Upvotes: 4

Toni
Toni

Reputation: 1852

Google recommends to use "another caching library" like StashPHP on its Github page:

https://github.com/google/google-api-php-client#caching

Upvotes: 0

mjmarianetti
mjmarianetti

Reputation: 1

In order to have multiple Google Analytics accounts logged in, you could set the Google_Client cache to Google_Cache_Null

Google_Client $client = new Google_Client();
....
$googleCache = new Google_Cache_Null();
$client->setCache($googleCache);

Don't forget to add (adjust according to your setup)

use Google_Client;
use Google_Cache_Null;

You can check the default google cache directory (ubuntu) with:

$ ls /temp/google-api-php-client/

Information:

Google_Client

Google_Cache_Null

Upvotes: -1

Joaquim d'Souza
Joaquim d'Souza

Reputation: 1516

We implemented our own cache that just drops the data on the floor:

namespace AppBundle\Factory;

use Google\Auth\CacheInterface;

class NullGoogleCache implements CacheInterface
{

    public function get($key, $expiration = false)
    {
        return false;
    }

    public function set($key, $value)
    {
        //do nothing
    }

    public function delete($key)
    {
        //do nothing
    }
}

Upvotes: 0

Related Questions