使用通过 ScriptApp.getAuthToken() 获得的 AuthToken 调用 GAS 中的 Web 应用



我创建了 2 个简单的独立脚本来测试授权工作流。第一个脚本是一个只有我才能访问的 Web 应用程序。

function doGet(e) {
return ContentService.createTextOutput(JSON.stringify({"message":"works!"}))
.setMimeType(ContentService.MimeType.JSON);
}

调用脚本通过 ScriptApp.getAuthToken(( 获取令牌,并向 Web 应用程序发出"GET"请求。

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'
}

不幸的是,当我收到"未经授权"响应时,它似乎不起作用。我最初的想法是令牌的范围为每个单独的脚本,但 GAS 文档指示相反,指出 ScriptApp 令牌在月情况下就足够了。

https://developers.google.com/apps-script/reference/script/script-app#getOAuthToken((

我将不胜感激任何帮助。

如果你还在找这个答案,这个答案怎么样?我认为当清单安装范围时,您可以使用带有范围的访问令牌访问 Web 应用程序。

部署网络应用程序:

部署 Web 应用的条件如下所示。

  • 在带有doGet()的项目上的脚本编辑器上。
    • 发布 -> 部署为 Web 应用
    • 对于"以下列方式执行应用:",请设置"我"。
    • 对于"谁有权访问应用:",设置"仅限我自己"。

在上述情况下,当"headers": {"Authorization":"Bearer " + token}不用于option时,会发生错误。因此,为了访问具有上述条件的Web应用程序,请添加以下2个范围。在您的情况下,需要以下范围才能授权。

https://www.googleapis.com/auth/drive
https://www.googleapis.com/auth/script.external_request

在您的情况下,需要上述 2 个范围。在只有https://www.googleapis.com/auth/script.external_request的情况下,会发生Unauthorized的错误。

将范围添加到清单:

请将上述作用域安装到清单 (appsscript.json(,如下所示。

  • 在带有call()的项目上的脚本编辑器上。
    • 查看 -> 显示清单文件
    • 请将以下oauthScopes添加到appsscript.json
      • "oauthScopes": ["https://www.googleapis.com/auth/script.external_request", "https://www.googleapis.com/auth/drive"]

响应:

在上面安装后,请尝试再次运行您的call()。在我的环境中,我检索了以下响应。

200.0
{"message":"works!"}

如果我误解了你的问题,我很抱歉。

最新更新