You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

通过API Gateway调用私有GCP Cloud Function时遭遇403 Forbidden错误

解决API Gateway访问私有Cloud Function的403禁止错误

问题根因

你的Cloud Function设置了--ingress-settings=internal-and-gclb,这个规则只放行VPC内部流量和Google Cloud负载均衡(GCLB)转发的流量。API Gateway的请求默认不在允许范围内,因此触发403禁止错误。

解决步骤

1. 给API Gateway服务账号添加调用权限

API Gateway需要具备调用目标Cloud Function的权限:

  • 找到API Gateway对应的服务账号,格式通常为apigateway-{网关名称}@你的项目ID.iam.gserviceaccount.com
  • 进入Cloud IAM控制台,给该账号添加Cloud Functions Invoker角色,作用域指定为你要访问的Cloud Function。

2. 将API Gateway的IP范围加入Cloud Function白名单

internal-and-gclb规则支持添加授权外部IP,把API Gateway的IP段加入允许列表:

  • 用命令查询API Gateway的静态IP:
    gcloud compute addresses list --filter="purpose=API_GATEWAY"
    
  • 更新Cloud Function配置,添加允许的IP范围:
    gcloud functions deploy 你的函数名 \
      --ingress-settings=internal-and-gclb \
      --set-env-vars=ALLOWED_IPS=查到的API_GATEWAY_IP段
    
    也可以直接在函数代码中添加IP校验逻辑,仅放行API Gateway的请求。

3. 通过Serverless VPC Access实现内部网络访问

如果API Gateway和Cloud Function处于同一VPC,或需要通过内部流量访问:

  • 创建Serverless VPC Access连接器
  • 在API Gateway的openapi.yaml配置文件中,给后端添加VPC连接器配置:
    x-google-backend:
      address: https://你的区域-项目ID.cloudfunctions.net/你的函数名
      vpc-connector: projects/项目ID/locations/区域/connectors/连接器名称
    

4. 检查API Gateway路由配置

确保openapi.yaml中的路由配置无误:

  • 确认x-google-backend的地址与Cloud Function的触发URL完全一致
  • 如果Cloud Function需要认证,需在x-google-backend中设置jwt-audience为函数的客户端ID,保证身份令牌能通过校验。

验证操作

重新部署API Gateway和Cloud Function后,用curl测试访问:

curl https://你的API网关地址/ping

若仍报错,查看Cloud Function的日志,确认具体拒绝原因(如IP未授权、权限不足等)。

内容的提问来源于stack exchange,提问作者Ariyan Ashfaque Mostafa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 09:37:20