如何编程连接脚本应用到Google Cloud Platform并解决403权限报错
如何通过编程方式将Apps Script应用连接到Google Cloud Platform
已知手动操作的配置界面参考如下:
现有通过Java客户端调用Apps Script API实现配置的代码如下:
File file3 = new File() .setName("appsscript") .setType("JSON") .setSource("{\n" + " \"timeZone\": \""+TimeZone.getDefault().toZoneId().toString()+"\",\n" + " \"dependencies\": {},\n" + " \"exceptionLogging\": \"STACKDRIVER\",\n" + " \"executionApi\": {\n" + " \"access\": \"ANYONE\"\n" + " } }"); Content content = new Content().setFiles(Arrays.asList(file1, file2, file3)); script.projects().updateContent(project.getScriptId(), content).execute(); Version version = new Version(); version.setVersionNumber(1); Version versions = script.projects().versions().create(project.getScriptId(), version).execute(); DeploymentConfig deploymentConfig = new DeploymentConfig(); deploymentConfig.setManifestFileName("appsscript"); deploymentConfig.setVersionNumber(versions.getVersionNumber()); Deployment deployment = script.projects().deployments().create(project.getScriptId(), deploymentConfig).execute(); Operation op = script.scripts().run(deployment.getDeploymentConfig().getScriptId(), request).execute();
执行到scripts.run接口时返回403权限错误,错误响应如下:
POST https://script.googleapis.com/v1/scripts/xxxx:run { "code": 403, "errors": [ { "domain": "global", "message": "The caller does not have permission", "reason": "forbidden" } ], "message": "The caller does not have permission", "status": "PERMISSION_DENIED" }
解决方案
核心问题
返回403是两个配置缺失共同导致的:
- 当前操作的Apps Script项目默认关联谷歌托管的内置GCP项目,这类项目不支持通过API自定义绑定关系,也不支持跨项目服务账号调用
- 调用接口的身份凭证、部署配置缺少必要的权限声明
修复步骤
- 提前在Google Cloud控制台创建标准GCP项目,复制项目编号备用
- 创建Apps Script项目时,在
Content参数中新增parentId字段,值为自建GCP项目的编号,直接将脚本项目归属到对应GCP下,跳过默认托管项目的创建流程 - 更新
appsscript.json清单文件,补充必要的OAuth权限范围声明,修改后内容示例:
{ "timeZone": "对应时区值", "dependencies": {}, "exceptionLogging": "STACKDRIVER", "executionApi": { "access": "ANYONE" }, "oauthScopes": [ "https://www.googleapis.com/auth/script.projects", "https://www.googleapis.com/auth/script.deployments", "https://www.googleapis.com/auth/script.processes" ] }
- 权限配置:
- 调用API使用的账号(用户账号/服务账号)需要绑定目标GCP项目的
Apps Script 管理员或编辑者角色 - 将调用账号的邮箱添加到Apps Script项目的协作者列表,授予编辑权限,即便是配置了
ANYONE访问权限,服务账号调用时仍需要单独添加协作者权限
- 调用API使用的账号(用户账号/服务账号)需要绑定目标GCP项目的
- GCP侧配置:进入对应GCP项目的OAuth同意屏页面,将发布状态设置为「生产中」,如果处于测试状态,需要将所有调用账号添加到测试用户列表
- 重新创建版本、部署后再调用
scripts.run接口即可正常执行。
内容的提问来源于stack exchange,提问作者Александр Хворостенко
相关产品推荐
相关产品推荐

