首页 > 解决方案 > Cloud Function 的端点返回 403 Forbidden

问题描述

我正在按照 Google 的教程为我的云功能设置端点。

当我尝试使用 URL 从浏览器访问端点时,service_name.a.run.app/function1我得到

Error: Forbidden
Your client does not have permission to get URL /function1GET from this server

作为上述教程的一部分和来自 Google 产品经理的回答,我通过授予 ESP 调用我的函数的权限来保护我的函数。

gcloud beta functions add-iam-policy-binding function1 --member "serviceAccount:id-compute@developer.gserviceaccount.com" --role "roles/cloudfunctions.invoker" --project "project_id"

我的openapi-functions.yaml

swagger: '2.0'
info:
  title: Cloud Endpoints + GCF
  description: Sample API on Cloud Endpoints with a Google Cloud Functions backend
  version: 1.0.0
host: HOST
x-google-endpoints:
- name: "HOST"
  allowCors: "true
schemes:
  - https
produces:
  - application/json
paths:
  /function1:
    get:
      operationId: function1
      x-google-backend:
        address: https://REGION-FUNCTIONS_PROJECT_ID.cloudfunctions.net/function1GET
      responses:
        '200':
          description: A successful response
          schema:
            type: string

请注意,我添加了

- name: "HOST"
  allowCors: "true'

到我的.yaml文件,因为我需要从托管在 Firebase 上的静态站点访问端点。

标签: google-cloud-platformgoogle-cloud-functionsgoogle-cloud-endpointsgoogle-cloud-rungoogle-cloud-iam

解决方案


我已按照您提到的教程进行操作,并且确实遇到了完全相同的错误。

关于权限和角色似乎没有错。

在挖掘了一下解决问题的方法是删除地址末尾的“<code>GET”。

所以openapi-functions.yaml会是这样的:

swagger: '2.0'
info:
  title: Cloud Endpoints + GCF
  description: Sample API on Cloud Endpoints with a Google Cloud Functions backend
  version: 1.0.0
host: [HOST]
schemes:
  - https
produces:
  - application/json
paths:
  /function-1:
    get:
      summary: Greet a user
      operationId: function-1
      x-google-backend:
        address: https://[REGION]-[PROJECT_ID].cloudfunctions.net/function-1
      responses:
        '200':
          description: A successful response
          schema:
            type: string

然后确保您正确执行了教程中提到的所有步骤(上述部分除外)。

如果在运行任何步骤时出现 Permissions Denied 错误,请尝试再次以sudo.

我也尝试添加与您相同的内容:

host: [HOST]
x-google-endpoints:
- name: [HOST]
  allowCors: "true"

一切运行良好。

请特别注意CONFIG_ID每个新部署都会发生的变化示例:

2019-12-03r0

然后它就像:

2019-12-03r1

如果部署步骤失败(它会显示一些成功的消息,但最终可能会失败),请确保删除现有的端点服务以避免出现问题:

gcloud endpoints services delete [SERVICE_ID]

您也可以使用以下内容为cloudfunctions.invoker所有用户赋予角色(仅用于测试)

gcloud functions add-iam-policy-binding function-1 \
 --member="allUsers" \
 --role="roles/cloudfunctions.invoker"

推荐阅读