Experimenting with using gcp service accounts to query gemini from a spreadsheet via the OAuth2 library. 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 OAuth2 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 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.
Bread is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.