Dxx
Dxx

Reputation: 934

Google Oauth2: Error refreshing the OAuth2 token, message: '{ "error" : "invalid_grant" }'

I have the following code running on my localhost to try and authenticate with Google Oauth2. After authenticating, it appears to work for a while. Then after a certain amount of time I'm getting this classic error:

Error refreshing the OAuth2 token, message: '{
"error" : "invalid_grant"
}'

I've looked at the previous times this issue was posted to StackOverflow, but the suggested solutions didn't seem to work for me.

I believe the access token is updated correctly (see code below). I also believe the server clock is synchronized correctly. What am I doing wrong?


    //$token retrieved from database
    $token = {"access_token":"xxx.xxx_xxxx-xxx","token_type":"Bearer","expires_in":3600,"refresh_token":"1\/xXxXxxxxxXXXxx","created":145490000}

    $google = new Google_Client();
    $google->setAccessType('offline');
    $google->setClientId($client_id);
    $google->setClientSecret($client_secret);
    $google->setRedirectUri($client_redirect_uri);
    $google->setAccessToken($token);
    if($google->isAccessTokenExpired()) {
      $google->refreshToken($token);
    }
    $token = $google->getAccessToken();
    $google->setAccessToken($token);

    //Some Database code to save the new $token
    ...

    $result = new \Google_Service_YouTube($google);

Upvotes: 3

Views: 7342

Answers (1)

Linda Lawton - DaImTo
Linda Lawton - DaImTo

Reputation: 116948

There are two posibple causes for Invalid_Grant

  1. server clock not sync with NTP. (solution fix the time)
  2. The refresh token has expired. (solution request authentication again)

You stated that your code works for a while then stops working. This makes me think your problem is nr 2.

Reasons why a refresh token will stop working:

  1. The user in question has revoked your authentication.
  2. If a refresh token hasn't been used for 6 months will automatically expire.
  3. Refresh token is based upon the project (Client Id) and the user. If the user authenticates your application you get a refresh token. If they do it again you get another refresh token. The first one will still work as will the second. You can have up to 26 live refresh tokens once the user authenticates your code for the 27 th time you will loose the first refresh token.

To solve your problem you need to try and figure out which of the 3 problems above has caused your refresh token to expire. I cant really help you much with that its going to require some detective work on your part.

Upvotes: 5

Related Questions