apps-script-oauth2 icon indicating copy to clipboard operation
apps-script-oauth2 copied to clipboard

Unreliable with setCache(CacheService.getUserCache())

Open andreask1 opened this issue 4 years ago • 0 comments

Using a cache seems to make it unreliable to get tokens in at least the following situation:

  • Two different services created
  • Services used within a library
  • Library embedded in an outer script
  • Library function called in the outer script with doPost

The following error is thrown randomly for one of the services. "Error: Access not granted or expired. Service_.getAccessToken (Service)". When service1 is working and I re-authenticate service2, then service1 stops working. However, when I remove setCache from both services, everything works reliable.

The following entry point in the example below does not work reliably when using setCache:

  • doPost(e) in outer script

All the other ones work reliably:

  • manualCall() in outer script
  • doPost(e) in Libary when used as standalone script
  • manualCall() in Libary when used as standalone script

For me it's not a big deal to not use the cache but this might help fixing the root cause or prevent others from hours of debugging when running into an "Access not granted or expired" error.

function doPost(e) {
  Library.webhook();
}
function manualCall() {
  Library.webhook();
}
function authCallback1(request) {
  return Library.authCallback1(request);
}
function authCallback2(request) {
  return Library.authCallback2(request);
}

Library: {
  function doPost(e) {
    webhook();
  }
  function manualCall() {
    webhook();
  }
  function webhook() {
    ...
    let service1 = OAuth2.createService('service1')
        .setCallbackFunction('authCallback1')
        .setPropertyStore(PropertiesService.getUserProperties())
        .setCache(CacheService.getUserCache())
    ...
    service1.getAccessToken(); //Random error
    ...
    let service2 = OAuth2.createService('service2')
        .setCallbackFunction('authCallback2')
        .setPropertyStore(PropertiesService.getUserProperties())
        .setCache(CacheService.getUserCache())
    ...
    service2.getAccessToken(); //Random error
    ...
  }
  function authCallback1(request) {
    ...
  }
  function authCallback2(request) {
    ...
  }
}

andreask1 avatar Oct 20 '21 19:10 andreask1