部署为Web应用程序的Google Apps脚本的身份验证问题

Q_C*_*Q_C 7 google-apps-script

我尝试使用UrlFetch和授权标头中的承载从第二个GAS调用部署的Apps脚本(作为Web应用程序,可由"任何人"访问)时遇到HTTP 401错误.脚本工作正常,持续数周,直到大约两周前.这是两个重现错误的小脚本.

脚本A - 部署为Web应用程序,可供"任何人"访问.

function doGet(e) {
  var params = e.parameter.params;
  console.info("Parameters : " + JSON.stringify(e.parameter));
  return ContentService.createTextOutput("Success");
}
Run Code Online (Sandbox Code Playgroud)

脚本B - 通过UrlFetch调用脚本A.

function callURL() {
  var param = {
    method      : "get",
    headers     : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
    followRedirects : true,
    muteHttpExceptions:true,
  };
  var url = "https://script.google.com/macros/s/<script_A_deployed_url>/exec?param1=test";
  var resp = UrlFetchApp.fetch(url,param);
  if(resp.getContentText() != "Success"){
    console.info(resp.getContentText());
    throw resp.getContentText();
  }
}
Run Code Online (Sandbox Code Playgroud)

Tan*_*ike 8

你能再次确认以下几点吗?

  1. 对于客户端,项目中除了你的客户端脚本还有其他功能吗?如果项目中只有脚本,那么访问Web Apps的范围是不够的。Drive API 的范围需要包含在访问令牌的范围内。
    • 您可以在文件 -> 项目属性 -> 范围中查看当前范围。
    • 例如,这些是以下范围。
      • https://www.googleapis.com/auth/drive.readonly
      • https://www.googleapis.com/auth/drive.files
      • https://www.googleapis.com/auth/drive
  2. 在我的日志中,当Who has access to the app:安装为 时Anyone,我确认从 2018 年 4 月 11 日开始,需要共享项目才能访问 Web Apps。这可能是由于谷歌的更新。
    • 请与用户共享 Web Apps 的项目,然后重试。
  3. 对于Web Apps服务器端,如果设置User accessing the web appExecute the app as:,请使用自己的浏览器授权范围。这个授权只需要做一次。

如果这些对你的情况没有用,我很抱歉。


Q_C*_*Q_C 6

田池为我指明了正确的方向。显然,最近在部署为 Web 应用程序的 Apps 脚本的身份验证机制中更改了一些内部规则。对于 B 脚本,UrlFetch 的默认范围是https://www.googleapis.com/auth/script.external_request,但看起来我们现在至少需要对 A 脚本的读取访问权限,这意味着我们还需要 Drive 范围。为了实现这一点,您可以例如在 B 脚本中使用此功能来授权它们。

function setScope() {
  DriveApp.getRootFolder();
}
Run Code Online (Sandbox Code Playgroud)