How to enable OAuth Google Script without needing to sign in every time token expires?

Viewed 64

This .gs code checks if the document is authorized, and if so runs a post request. I am trying to only have to provide OAuth once rather than every time the token expires, any advice is appreciated!

function Gmail() {

  if (service.hasAccess()) {
  var toolKeyFinal = service.getAccessToken();

//*******request would run with token here********

   }
  else{
      var authorizationUrl = service.getAuthorizationUrl();
      var string = toolName+" Authorization (then try formula again ),"+authorizationUrl;
      var auth = [{}];
      return string.split(",")
  }
}

  
function getServiceGmail() {
  return OAuth2.createService('Gmail')
      .setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
      .setTokenUrl('https://accounts.google.com/o/oauth2/token')
      .setClientId('CLIENT-ID')
      .setClientSecret('CLIENT-SECRET')
      .setCallbackFunction('authCallback')
      .setPropertyStore(PropertiesService.getDocumentProperties())
      .setScope('https://mail.google.com/');
};

/**
 * Handles the OAuth callback.
 */
function authCallback(request) {
  var service = getServiceGmail();
  var authorized = service.handleCallback(request);
  if (authorized) {
    return HtmlService.createHtmlOutput(
    "<script>window.top.location.href='https://REDIRECT.com';</script>"
  );
    //return HtmlService.createHtmlOutput('PowerSheet authorization successful for your Google Sheet! You can close this tab.');
  } else {
    return HtmlService.createHtmlOutput('You did not provide authorization. Please close this tab and try again.');
  }
}
1 Answers

According to the documentation:

A Google Cloud Platform project with an OAuth consent screen configured for an external user type and a publishing status of "Testing" is issued a refresh token expiring in 7 days.

So, for external(aka. user-facing) Apps, you have to upgrade your publishing status to "In production", by going through Google's review and verification process.

Also, since you're using a restricted scope (https://mail.google.com/) you'll also have to undergo a security assessment which could run you anywhere from US$8k to US$75K (see Security Assessment)

Related