如何正确配置GAS Web App通过OAuth2以本人身份调用GAS API可执行程序
问题核心原因
你当前的配置和代码共有4个关键错误导致权限报错:
- doGet函数执行顺序错误,未判断授权状态就先调用了需要token的请求函数
- OAuth权限范围缺失调用Apps Script执行API的必需权限
- GCP OAuth同意屏幕配置和Web App访问权限不匹配
- 未确认API可执行程序的部署ID是否正确
修复步骤
1. 修正doGet执行顺序
将API请求逻辑移到授权校验通过之后,修改后的代码如下:
function doGet(e) { var myParam = "someParam"; console.log(myParam); var appsScriptService = getService(); if (!appsScriptService.hasAccess()) { // 未授权时只返回授权链接 var authorizationUrl = appsScriptService.getAuthorizationUrl(); var htmlOutput = HtmlService.createHtmlOutput('<a href="' + authorizationUrl + '" target="_blank">Authorize</a>.'); htmlOutput.setTitle('GAS Authentication'); return htmlOutput; } else { // 授权通过后再发起API请求 var apiExecResponse = makeRequest('doPost', [myParam]); console.log(apiExecResponse); console.log("It worked: " + myParam + " " + apiExecResponse); var htmlOutput = HtmlService.createHtmlOutput("<p>It worked: " + myParam + " " + apiExecResponse + "</p>"); htmlOutput.setTitle("The Results"); return htmlOutput; } }
2. 补全OAuth权限范围
- 找到getService函数中的
setScope配置,添加执行API必需的权限:
.setScope('https://www.googleapis.com/auth/script.external_request https://www.googleapis.com/auth/spreadsheets https://www.googleapis.com/auth/script.run')
- 同步修改webApp的
appsscript.json中的oauthScopes配置:
"oauthScopes": [ "https://www.googleapis.com/auth/script.external_request", "https://www.googleapis.com/auth/spreadsheets", "https://www.googleapis.com/auth/script.run" ]
3. 调整GCP OAuth同意屏幕配置
- 如果你使用的是个人普通Google账号(非企业Workspace账号),需要将同意屏幕类型从
Internal改为External,测试状态下将你自己的账号添加到测试用户列表;如果需要所有用户可访问,将应用发布为正式版本即可。 - 将
script.google.com添加到同意屏幕的已授权域名列表中。
4. 验证部署ID
确认makeRequest函数中apiExecUrl里的脚本ID,是apiExec部署为API可执行程序后生成的部署ID,不是apiExec项目的编辑器ID,可在apiExec的部署管理页面获取正确ID。
5. 重置生效
- 保存所有修改后重新部署webApp和apiExec,确保使用最新版本。
- 执行一次以下代码清空旧的无效凭证:
function clearOldToken() { PropertiesService.getScriptProperties().deleteProperty('oauth2.apiExecService'); }
- 重新访问webApp,点击授权链接完成授权即可正常调用。
内容的提问来源于stack exchange,提问作者Brandon
相关产品推荐
相关产品推荐

