Search code examples
javascriptoauth-2.0google-apistrapi

Google API oauth2 refresh_token becomes invalid after a certain time


I've got a problem with Google API and refresh token.

return axios.post("https://accounts.google.com/o/oauth2/token", {
   client_id: clientId,
   client_secret: clientSecret,
   refresh_token: querystring.unescape(refresh_token),
   grant_type: "refresh_token",
})
.then((response) => {
   return response.data.access_token;
})
.catch((err) => console.log("error GetTokenWithRefresh: ", err.response))

This works fine. I get my new token. (I use this request for tests each time I need to write into excel document). But after a certain time, my refresh_token becomes invalid

{
    "error": "invalid_grant",
    "error_description": "Token has been expired or revoked."
}

My google account used to grant access to app is far under the limit of refresh tokens. It still has app in authorised applications in security on my Google account. It's as if the refresh_token had the same behavior as a classic token.

If you have any idea where the problem may be coming from, I would be very grateful!

Have a nice day !


Solution

  • That's not a problem - it is standard OAuth behaviour, where you first configure lifetimes, eg:

    • Access token lasts 60 minutes
    • Refresh token lasts for 12 hours

    EXPIRY

    Access token acts as a short lived API message credential - it can be renewed silently without impacting the end user. When the access token expires the caller receives a 401 HTTP status.

    When a 401 is received, the client uses the refresh token to get a new access token. Eventually the refresh token also expires and the token renewal attempt returns an invalid_grant error. The user must then be redirected to re-authenticate.

    VISUALISATION

    Feel free to run my Online Single Page Demo App to understand how this looks. In my SPA the refresh token is wrapped in an HTTP only cookie and the access token is stored in the browser.