OAuth v2 (Google API) expiry Access Token

apigoogle analyticsgoogle-oauthoauth

I am building an integration component using a graphical framework who has a pre-build OAuth2 connector.
This framework required following fields for OAuth v2:

  • Grant type
  • Scope
  • Auth Server URL
  • Client Id
  • Client Secret
  • Access Token
  • Refresh token

I need to get data from Google Analytics API, so I went to Google Dev Console
(https://console.developers.google.com/project/927890000889/apiui/credential). I generated a 'Client ID for web application'. From the parameter of this object I was able to fill some of the parameters above

  • Grant type : 'authorisation_code'
  • Client Id : 'RANDOMCHARSam5o37nsiu730d.apps.googleusercontent.com'
  • Client Secret : 'RANDOMCHARSiSwBA5OH5qYLUa'

Then using Google Oauth Playground (https://developers.google.com/oauthplayground) I was able to fill the missing bits

Everything works fine, I am authorised to access and I get data from Google Analytics, but just for a while, after few minutes if I retry I receive an authorisation failure error.
I believe that the problem is related to the expiration of the Access Token, but I don't know how to solve that.
Worth to mention that this activity it's batch (no human interaction), so nobody can request a new access token.
The integration framework is not extensible (I cannot write code to renew the code) so I believe there's a way to get a access token that never expire or some other mechanism to achieve the same result.

Bottom line, I am not sure if I approached the requirement correctly since the beginning (Client ID for web application).

Any help is much appreciated,
Giovanni

Best Answer

Access tokens typically expire after 60 minutes. If you have a refresh token you can use the refresh token to get a new (valid) access token.

This doc explains how to do that:
https://developers.google.com/accounts/docs/OAuth2WebServer#refresh

To answer your overarching question, yes, you are approaching everything correctly. All you need to do is handle the case where the access token has expired by refreshing it. Also, when you originally requested the access token the response should tell you how long it's valid for, so you should only refresh that token if it's expired.

Related Topic