使用Google Cloud Tasks触发Gen2云函数遇403权限拒绝问题排查
问题:Cloud Tasks触发Gen2 Cloud Function报403权限错误
报错信息
- 任务触发函数时返回:
PERMISSION_DENIED(7): HTTP status code 403 - Cloud Function日志警告:
The request was not authenticated. Either allow unauthenticated invocations or set the proper Authorization header. Read more at https://cloud.google.com/run/docs/securing/authenticating Additional troubleshooting documentation can be found at: https://cloud.google.com/run/docs/troubleshooting#unauthorized-client
相关代码
this.client = new v2beta3.CloudTasksClient(); this.queuePath = this.client.queuePath( this.envService.gcp.project, this.envService.gcp.queue.region, this.envService.gcp.queue.name, ); const body = Buffer.from(JSON.stringify(payload)).toString('base64'); const task = { httpRequest: { httpMethod: 'POST' as const, url: this.envService.gcp.functions.myFunction, headers: { 'Content-Type': 'application/json', }, body, }, }; task.httpRequest['oidcToken'] = { serviceAccountEmail: this.envService.gcp.serviceAccountEmail, audience: this.envService.gcp.functions.myFunction, }; await this.client .createTask({ parent: this.queuePath, task, }) .catch((e: Error) => { console.log(e, e.stack); this.logger.error(e.message, null, QueueService.name); throw new InternalServerErrorException(); });
已确认的配置与权限
- 配置变量(项目、函数地址、服务账号邮箱、区域、队列名称)均正确,且能在Cloud Console中看到创建的任务。
- 服务账号已配置:
- 为Cloud Function添加
Cloud Function Invoker角色 - 为队列添加
Cloud Task Admin和Cloud Task Enqueuer角色
- 为Cloud Function添加
- 任务日志中显示:
authorizationHeader: 'oidcToken'
预期此处应为实际令牌,不确定该信息是否影响权限验证。
运行环境说明
Node.js服务器运行在本地,已激活目标服务账号(gcloud auth list可确认状态),且已设置环境变量GOOGLE_APPLICATION_CREDENTIALS指向服务账号的key.json文件路径。
已尝试的操作
- 为
allUsers添加Cloud Function的Invoke权限,并移除任务配置中的oidcToken - 使用个人邮箱登录gcloud,为服务账号添加
Service Account User角色
疑问点
不确定错误是来自创建任务时的凭据缺失,还是任务触发函数时的凭据缺失,也不清楚这两个操作是否属于独立的请求。
内容的提问来源于stack exchange,提问作者Loïc Combis
相关产品推荐
相关产品推荐

