A
A
Alexey Markov2018-12-07 01:37:37
Google
Alexey Markov, 2018-12-07 01:37:37

How to organize the storage of tokens for several users in the Google client?

Good day.
I am writing my own interface for working with google drive, but working with the client slows me down a lot.
A persistent problem with the token is invalid_grant or many others related to the token.

$client = new \Google_Client();

        $client->setClientId('myid.apps.googleusercontent.com');
        $client->setClientSecret('dsafasddadasdadad');
        $client->setRedirectUri($redirect_uri);
        $client->addScope(\Google_Service_Drive::DRIVE);
        $client->setAccessType("offline");

        // Запрос на подтверждение работы с Google-диском
        if (isset($_REQUEST['code'])) {
            $token = $client->authenticate($_REQUEST['code']);
            $_SESSION['accessToken'] = $token;
            header('Location:' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
        } elseif (!isset($_SESSION['accessToken'])) {
            header('Location:' . filter_var($client->createAuthUrl(), FILTER_SANITIZE_URL));
        }

        try {
            // Присваиваем защитный токен для работы с Google-диском
            $client->setAccessToken($_SESSION['accessToken']);
        } catch (\Exception $e) {
            die($e->getMessage() . " — " . var_dump($_SESSION));
        }

With this design, it periodically throws an error with tokens that they are outdated or incorrect (unfortunately, I did not save the listing of the error, you need to wait for the tokens to expire).
When using the construction $client->isAccessTokenExpired() and $client->getRefreshToken() (taken from the docks according to the standard), the error periodically occurs invalid_grant, Bad Request
Who wrote such constructions for a plurality of users? I've been trying this problem for a week now, I've rummaged through all the English-language resources, I haven't found a sane example with $client->isAccessTokenExpired() and $client->getRefreshToken() for the application

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
SerJook, 2018-12-11
@SerJook

I did not see where you have a lot of users here. Do you mean the number of users of your site?
You store data in a session, each has its own session, so in theory they should not overlap.
Firstly, you do not check what the call returned to you, but immediately write the result to the session. Make a check like Then, you need to update the access token if it has expired. Something like:$client->authenticate($_REQUEST['code']);

$client->setAccessToken($_SESSION['accessToken']);

if ($client->isAccessTokenExpired()) {
        $new_token = $client->refreshToken(null);
        if (isset($new_token['access_token'])) {
            $_SESSION['accessToken'] = $new_token;
        }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question