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

时间:2018-04-25 11:51:32

标签: google-apps-script

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

脚本A - 部署为网络应用,可供“任何人”访问。

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

脚本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();
  }
}

2 个答案:

答案 0 :(得分:3)

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

function setScope() {
  DriveApp.getRootFolder();
}

答案 1 :(得分:2)

您能否再次确认以下几点?

  1. 对于客户端,除了项目中客户端的脚本之外,是否还有一些功能?如果项目中只有脚本,则访问Web Apps的范围是不够的。 Drive API的范围必须包含在访问令牌的范围内。
    • 您可以在File - &gt;中看到当前的范围。项目属性 - &gt;作用域。
    • 例如,这些是以下范围。
      • RewriteEngine on RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule .*xerowebhook /webhooklanding.php [QSA,L,END] RewriteRule ^ index.php [QSA,L]
      • https://www.googleapis.com/auth/drive.readonly
      • https://www.googleapis.com/auth/drive.files
  2. 在我的日志中,当https://www.googleapis.com/auth/drive安装为Who has access to the app:时,我确认从2018年4月11日起,需要共享项目才能访问Web Apps。这可能是由于Google的更新。
    • 请与用户分享Web Apps项目,然后重试。
  3. 对于Web Apps服务器端,如果为Anyone设置User accessing the web app,请使用自己的浏览器授权范围。此授权只需要执行一次。
  4. 如果这些对你的情况没用,我很抱歉。