问题
I created 2 simple standalone scripts to test the authorization workflow. The first script is a web app that is accessible only to me.
function doGet(e) {
return ContentService.createTextOutput(JSON.stringify({"message":"works!"}))
.setMimeType(ContentService.MimeType.JSON);
}
The calling script gets the token via ScriptApp.getAuthToken() and makes a 'GET' request to the web app.
function call() {
var token = ScriptApp.getOAuthToken();
var header = {"Authorization":"Bearer " + token};
var options = {
"method":"GET",
"headers": header,
"muteHttpExceptions": true
};
var url = 'APP_URL';
var response =UrlFetchApp.fetch(url, options);
Logger.log(response.getResponseCode()); //returns 401
Logger.log(response.getContentText()); // returns 'Unauthorized'
}
Unfortunately, it doesn't seem to work as I get the 'Unauthorized' response. My initial thought was that the token is scoped to each individual script, but GAS documenation indicates the contrary, stating that the ScriptApp token would be sufficient in month cases.
https://developers.google.com/apps-script/reference/script/script-app#getOAuthToken()
I would appreciate any help.
回答1:
If you are still looking for this answer, how about this answer? I think that when the scopes are installed by Manifests, you can access the Web Apps using the access token with the scopes.
Deploy Web Apps :
The condition for deploying Web Apps is as follows.
- On script editor on the project with
doGet().- Publish -> Deploy as web app
- For "Execute the app as:", set "Me".
- For "Who has access to the app:", set "Only myself".
At above condition, when "headers": {"Authorization":"Bearer " + token} is not used for option, the error occurs. So in order to access to Web Apps with above condition, please add the following 2 scopes. In your case, the following scopes are required to authorize.
https://www.googleapis.com/auth/drive
https://www.googleapis.com/auth/script.external_request
In your case, the above 2 scopes are required. In the case of only https://www.googleapis.com/auth/script.external_request, the error of Unauthorized occurs.
Add scopes to Manifests :
Please install above scopes to Manifests (appsscript.json) as follows.
- On script editor on the project with
call().- View -> Show manifest file
- Please add the following
oauthScopestoappsscript.json."oauthScopes": ["https://www.googleapis.com/auth/script.external_request", "https://www.googleapis.com/auth/drive"]
Response :
After it installed above, please try to run your call() again. In my environment, I retrieved the following response.
200.0
{"message":"works!"}
If I misunderstand your question, I'm sorry.
来源:https://stackoverflow.com/questions/45534493/using-authtoken-obtained-via-scriptapp-getauthtoken-to-call-web-apps-in-gas