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

Dropping Scopes with Service Account #484

Closed bradlm closed 5 months ago

bradlm commented 5 months ago

Experimenting with using gcp service accounts to query gemini from a spreadsheet. Using the example from the Google Workspace Installable Triggers guide.

function test() {
const service = OAuth2.createService(<ServiceName>)
      .setTokenUrl('https://accounts.google.com/o/oauth2/token')
      .setPrivateKey(<serviceAccountPrivateKey>)
      .setClientId(<serviceAccountAddress>)
      .setPropertyStore(PropertiesService.getUserProperties())
      .setScope([
        "https://www.googleapis.com/auth/spreadsheets.currentonly",
        "https://www.googleapis.com/auth/script.external_request",
        "https://www.googleapis.com/auth/cloud-platform"
      ]);

  console.log('access: ', service.hasAccess(), 'scopes: ', service.scope);

  if (!service.hasAccess()) {
    console.error('Authentication error: ', service.getLastError());
    return;
  }

  const options = {
    method: "post",
    contentType: 'application/json',   
    headers: {
     Authorization: `Bearer ${service.getAccessToken()}`,
    },
    payload: JSON.stringify({...})
  };

  let response = UrlFetchApp.fetch(<url>, options);
  ...
}

When I run it, the log shows access: true scopes: undefined, and I get the following error:

Exception: Request failed for <url> returned code 403. Truncated server response: {
  "error": {
    "code": 403,
    "message": "Request had insufficient authentication scopes.",
    "status": "PERMISSION_DENIED",
    "details":... (use muteHttpExceptions option to examine full response)

I've tried copying the setScopes function out of the repo and running it on my scope array to make sure I wasn't just doing the input wrong, and it was properly generating a space-delimited list of scopes. Tried passing a space-delimited list string instead of an array, still comes back undefined. As best as I've been able to tell, the code is largely the same as whats found in the example I linked above.

The service appears to be successfully getting a token, but something is happening to the scopes. Any insight is appreciated.

bradlm commented 5 months ago

I think this may have had something to do with the service account being too fresh? Ran the same code today, and it works as expected. Can no longer reproduce, closing the issue.