Search code examples
google-apps-scriptgoogle-oauth

Detect access token expiration when invoking Google APIs


I have a Google Apps Script that is deployed as API Executable. I am able to invoke it from my java based web application. But, it fails only sometimes with Authorization is required to perform that operation. I have done the analysis and found that it fails because Apps Script returns this error if the access token expiration time is less than 6 minutes. There is a reason behind why Apps Script behaves this way, which is beyond the scope of this question. But, the solution to this is to generate a new access_token if the expiration time is less than 6minutes.

I am using Java Google Client Library to manage the access tokens:

GoogleCredential credential = new GoogleCredential.Builder()
                                    .setTransport(httpTransport)
                                    .setJsonFactory(jsonFactory)
                                    .setClientSecrets("<<clientId>>", "<<clientSecret>>")
                                    .build();
credential.setRefreshToken("<<refresh_token>>");

Using the above credential I am creating the Script object:

Script scriptService = new Script.Builder(httpTransport, jsonFactory, credential).setApplicationName("test").build();

Invoke the Apps Script:

scriptService.scripts().run("test script");

The client library takes care of generating the access token, store it in-memory and on expiration invokes the OAuth API to generate a new token.

Now, I would need your suggetions to:

  1. check if the expiration time of the access token is less than 6 minutes
  2. if yes, then generate the new access token

Solution

  • Following is the code to find the remaining time for the token to expire and generate the new access token:

    check if the expiration time of the access token is less than 6 minutes

    credential.getExpiresInSeconds()
    

    if yes, then generate the new access token

    credential.refreshToken()