googleworkspace / apps-script-oauth2

An OAuth2 library for Google Apps Script.
https://developers.google.com/apps-script/
Apache License 2.0
1.56k stars 429 forks source link

Unreliable with setCache(CacheService.getUserCache()) #332

Open andreask1 opened 3 years ago

andreask1 commented 3 years ago

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

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:

All the other ones work reliably:

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) {
    ...
  }
}