Which are the right scopes to run request on Apps Script API

1.4k views Asked by At

I'm using Apps Script API to run a function with the service account's credential. I added all scopes required in Rest resource API https://developers.google.com/apps-script/api/reference/rest/v1/scripts/run.

But when i run this script below it failed.

function run(){

 var CREDENTIALS = {
  "private_key": "Your Private key",
  "client_email": "Your Client email",
  "client_id": "Your Client ID",
  "user_email": "Your Email address",
  "api_key": "Your API key"
 };
 var service = getService(CREDENTIALS.client_email,CREDENTIALS.private_key);
  service.reset();
  if (service.hasAccess()) {
    var url = 'https://script.googleapis.com/v1/projects/[SCRIPT ID]:run';
    var body = {
      "function": [FUNCTION NAME]
    };
    var params = {
      headers: {
        Authorization: 'Bearer ' + service.getAccessToken()
      },
      method: 'post',
      playload : JSON.stringify(body),
      contentType: 'application/json',
      muteHttpExceptions: true
    };
    var response = UrlFetchApp.fetch(url, params);
    Logger.log(response);
  }
  else {
    Logger.log(service.getLastError());
  }
}

function getService(email, privateKey) {
  return OAuth2.createService('Service Account')
      // Set the endpoint URL.
      .setTokenUrl('https://oauth2.googleapis.com/token')

      // Set the private key and issuer.
      .setPrivateKey(privateKey)
      .setIssuer(email)

      // Set the name of the user to impersonate. This will only work for
      // Google Apps for Work/EDU accounts whose admin has setup domain-wide
      // delegation:
      // https://developers.google.com/identity/protocols/OAuth2ServiceAccount#delegatingauthority
      .setSubject([USER EMAIL])

      // Set the property store where authorized tokens should be persisted.
      .setPropertyStore(PropertiesService.getScriptProperties())

      // Set the scope. This must match one of the scopes configured during the
      // setup of domain-wide delegation.
      .setScope('https://www.googleapis.com/auth/script.external_request');
}

I've got a 404 Error and I think it comes from the scopes list. So I can't run a script deployed as an API Executable with the OAuth2.0 token. Which scopes should I choose to run a function via an HTTP request?

3

There are 3 answers

0
TheAddonDepot On

In your run function, for the params object you should have payload not playload.

2
Tanaike On
  • You want to use Apps Script API with the service account.
  • You want to achieve this using Google Apps Script.

If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.

Issue and workaround:

Unfortunately, in the current stage, the method of scripts.run in Apps Script API cannot be used with the service account. The official document says as follows. About this, when I tested this, I could confirm that the method of scripts.run in Apps Script API cannot be used with the service account.

Warning: The Apps Script API doesn't work with service accounts.

From above situation, as the workaround, how about using the access token retrieved by OAuth2? In order to use the Apps Script API with OAuth2, it is required to link Cloud Platform Project to Google Apps Script Project. About this, you can see the flow for linking them at here.

Note:

References:

If this was not the direction you want, I apologize.

Added:

  • You want to make several users run the script as the owner who is you.

From your replying, I could understand like above. When Apps Script API is used for above situation, the credential information is required to give each user. When each user uses the access token retrieved by your credential information, your goal can be achieve. But I cannot recommend this. So in your case, I would like to use Web Apps to achieve your goal. The flow is as follows.

1. Prepare script.

Please prepare your script. For example, in the current stage, you want to make users run a function of myFunction(), please put the following sample script.

function doGet(e) {
  var values = e; // When you want to give the values by requesting, you can use the event object like "e".
  var res = myFunction(values);
  return ContentService.createTextOutput(res);
}
  • In this case, the GET method is used. When you want to only run the function, you can use this script. When you want to run the function by giving the large data, you can use doPost() instead of doGet().

2. Deploy Web Apps.

  1. On the script editor, Open a dialog box by "Publish" -> "Deploy as web app".
  2. Select "Me" for "Execute the app as:".
    • By this, the script is run as the owner.
    • Here, when "Anyone" is set, the script is run as each user. In this case, it is required to share the script to each user. And the access token is required to be used. Please be careful this.
  3. Select "Anyone, even anonymous" for "Who has access to the app:".
    • In this case, no access token is required to be request. I think that as the test case, I recommend this setting.
    • Of course, you can also use the access token. At that time, please set this to "Anyone".
  4. Click "Deploy" button as new "Project version".
  5. Automatically open a dialog box of "Authorization required".
    1. Click "Review Permissions".
    2. Select own account.
    3. Click "Advanced" at "This app isn't verified".
    4. Click "Go to ### project name ###(unsafe)"
    5. Click "Allow" button.
  6. Click "OK".
  7. Copy the URL of Web Apps. It's like https://script.google.com/macros/s/###/exec.
    • When you modified the Google Apps Script, please redeploy as new version. By this, the modified script is reflected to Web Apps. Please be careful this.

3. Run the function using Web Apps.

This is a sample curl command for executing myFunction with Web Apps. Please set your Web Apps URL. At above settings of Web Apps, each user can access by the following curl command.

curl -GL \
  -d "key=value" \
  "https://script.google.com/macros/s/###/exec"
  • When key=value is used as the query parameter like above, at doGet(e), you can retrieve value using e.parameter.key.

References:

0
Jescanellas On

You can deploy the script as a Web App. To do so, go to Publish > Deploy as web app. Set the Execute the app as: field to Me (youremail). This way you can share the script as a browser link, and any user will run the script with your credentials.

You can add a some user interface with a confirmation message so the users know they have successfully executed the script. You can find the documentation in this link.