当Web App设为「任何Google账号用户」时,如何用UrlFetchApp连接Apps Script Web App
问题场景
- 独立Google Apps Script项目部署为Web App,包含以下测试函数:
function doGet(e) { Logger.log(e); return ContentService.createTextOutput('Get OK'); } function doPost() { Logger.log("doPost"); return ContentService.createTextOutput('Post OK'); } - 另一个绑定表格的Apps Script项目通过
doConnect函数请求该Web App:function doConnect() { var response = UrlFetchApp.fetch( "https://script.google.com/macros/s/XXXXXXXXX/exec", { method: "get", headers: { Authorization: "Bearer " + ScriptApp.getOAuthToken() }, muteHttpExceptions: true } ); Logger.log(response.getContentText()); } - 当Web App访问权限设为「任何人」时请求正常,改为「任何拥有Google账号的人」时返回
Error 401 Unauthorized,但直接在浏览器中访问URL可正常获取结果。后续计划将doConnect绑定到表格按钮,以所有者权限刷新受保护单元格。
解决方法
补充OAuth权限范围
打开脚本的appsscript.json文件(若未显示,可通过编辑器菜单「查看」→「显示清单文件」开启),添加必要的权限范围:{ "oauthScopes": [ "https://www.googleapis.com/auth/script.external_request", "https://www.googleapis.com/auth/script.webapp.deploy" ] }前者是
UrlFetchApp发起外部请求所需权限,后者确保能访问Web App资源。添加重定向控制参数
Google对Web App请求可能会触发重定向,导致Authorization头丢失,在请求配置中添加followRedirects: false:function doConnect() { var response = UrlFetchApp.fetch( "https://script.google.com/macros/s/XXXXXXXXX/exec", { method: "get", headers: { Authorization: "Bearer " + ScriptApp.getOAuthToken() }, muteHttpExceptions: true, followRedirects: false } ); Logger.log(response.getContentText()); }重新部署Web App
修改访问权限后必须重新部署为新版本,确保设置生效:- 部署时选择「新版本」,而非测试部署
- 执行权限根据需求选择「我(部署者)」或「用户访问Web App时」
- 确认访问权限设为「任何拥有Google账号的人」
重新授权脚本
在脚本编辑器中重新运行doConnect函数,触发完整的OAuth授权流程。若之前授权过,可先在Google账号的「安全设置」→「第三方应用访问权限」中撤销该脚本权限,再重新授权。
内容的提问来源于stack exchange,提问作者Kuba D
相关产品推荐
相关产品推荐

