Reputation: 43
I wrote a test web app using apps script. I deployed it to execute as "User accessing the web app" and set access to "Anyone who has a Google account". I then tried to call the web app function from another script which acts as the client. I did all of this while logged into my google account, both web app and client are in the same browser window (in different tabs). But I always get a 401 error. I then tried adding some oauthScopes to the appsscript.json file for the client script, but this didn't help. Any help solving this would be appreciated.
Web app code:
function doPost(e) {
if(typeof e !== 'undefined') {
let par = e.parameter;
let retval = par.x*3;
let retobj = {"retval":retval};
return ContentService.createTextOutput(JSON.stringify(retobj));
}
}
Client code:
function callWebApp(x) {
Logger.log("starting call webapp");
var payload = {
"info" : "some text",
"x" : 3,
"type" : "post",
};
var options = {
"method" : "POST",
"payload" : payload,
"followRedirects" : true,
"muteHttpExceptions": true
};
var result = UrlFetchApp.fetch(urlString, options);
Logger.log(result.getResponseCode());
if (result.getResponseCode() == 200) {
Logger.log('got response');
var params = JSON.parse(result.getContentText());
Logger.log(params.retval);
}
return 1;
}
appscript.json for client:
{
"timeZone": "America/New_York",
"dependencies": {
},
"exceptionLogging": "STACKDRIVER",
"runtimeVersion": "V8",
"oauthScopes": [
"https://www.googleapis.com/auth/script.deployments",
"https://www.googleapis.com/auth/script.deployments.readonly",
"https://www.googleapis.com/auth/script.external_request",
"https://www.googleapis.com/auth/script.projects",
"https://www.googleapis.com/auth/script.processes",
"https://www.googleapis.com/auth/script.projects.readonly"
]
}
Execution log: 7:47:30 PM Notice Execution started 7:47:30 PM Info starting call webapp 7:47:30 PM Info 401.0 7:47:30 PM Notice Execution completed
Upvotes: 2
Views: 2695
Reputation: 201348
Execute as: User accessing the web app
and Who has access: Anyone with Google account
and you want to access to the Web Apps using the script (in this case, it's Google Apps Script.), it is required to request to the Web Apps by including the access token in the request header.https://www.googleapis.com/auth/drive.readonly
and/or https://www.googleapis.com/auth/drive
to your current scopes in your client.urlString
is not declared. Although I'm not sure whether this might be declared elsewhere, please confirm it again.When these points are reflected to your script, it becomes as follows.
var options = {
"method" : "POST",
"payload" : payload,
"followRedirects" : true,
"muteHttpExceptions": true
};
To:
var options = {
"method": "POST",
"payload": payload,
"muteHttpExceptions": true,
"headers": {authorization: "Bearer " + ScriptApp.getOAuthToken()}
};
Upvotes: 2