Good day, everyone!
While administrating my website, sometimes I need to export data to Google Sheets.
I connected to Google API with a service account according to this instruction and everything seemd working well for a while.
But later I started to notice 401 error ACCESS_TOKEN_EXPIRED when I am trying to make an API request to google.
It disappears after I republish the website or after I open it in the incognito browser mode. Manual deletion of “sitename.sid” cookie helps as well.
But of course this needs a proper solution.
Is this a bug or I made some wrong settings?
Or using JWT and google Oauth2 needs some additional tweaking, beside steps in instruction?
Because I see many thorough instructions by @pswebhere and here regarding tokens refresh issue with Google API. Is this still relevant now?
The default behavior is that the access_token and refresh_token are stored in a session. It also stores the expires there. Each time the oauth is used it checks if there is an access_token stored in the session and it checks the expires if it isn’t expired. If it is expired it uses the refresh_token to refresh the token.
If you choose Google as Service in the OAuth2 provider it should have the correct parameters. If you added it as a custom you have to add the param access_type with the value offline, without this param it will not give you a refresh_token.
With service account and the JWT flow the access_token expires after 1 hour.
You could create a server action with a setValue step in it, there use {{$_SESSION}} for the value. Make sure output is checked and then do first make your google call so it creates an access_token and then the server action with the setValue which should return the content of what is in the session. It should contain gsheets_oauth_access_token, gsheets_oauth_refresh_token and gsheets_oauth_expires.
Access tokens issued by the Google OAuth 2.0 Authorization Server expire after the duration provided by the expires_in value. When an access token expires, then the application should generate another JWT, sign it, and request another access token.
We reuse the JWT each time, that is probably the problem, it should generate a new JWT each time for new authorization.
Here an update that should force the JWT to be generated new each time. When the access_token is expired it will be removed from the session and it will use the JWT again to create a new access_token.