使用通过 ScriptApp.getAuthToken() 获取的 AuthToken 在 GAS 中调用 Web 应用程序

Ant*_*iev 3 google-apps-script

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

function doGet(e) {

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

}
Run Code Online (Sandbox Code Playgroud)

调用脚本通过 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'

}
Run Code Online (Sandbox Code Playgroud)

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

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

我将不胜感激任何帮助。

Tan*_*ike 7

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

部署网络应用程序:

部署Web Apps的条件如下。

  • 在项目的脚本编辑器上 doGet().
    • 发布 -> 部署为 Web 应用程序
    • 对于“将应用程序执行为:”,设置“我”。
    • 对于“谁有权访问应用程序:”,设置“只有我自己”。

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

https://www.googleapis.com/auth/drive
https://www.googleapis.com/auth/script.external_request
Run Code Online (Sandbox Code Playgroud)

在您的情况下,需要上述 2 个范围。在 only 的情况下https://www.googleapis.com/auth/script.external_request,误差为Unauthorized会出现。

将范围添加到清单:

appsscript.json按如下方式将上述范围安装到清单 ( ) 中。

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

回复 :

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

200.0
{"message":"works!"}
Run Code Online (Sandbox Code Playgroud)

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