Google Cloud API Gateway 在使用 firebase 身份验证时无法调用 Cloud 运行 服务

Google Cloud API Gateway can't invoke Cloud Run service while using firebase auth

我正在使用具有 firebase JWT 授权的 API 网关(以便用户可以使用 google 登录)将请求转发到云 运行 服务和一项云功能服务.

这是我的 API 网关配置的样子:

swagger: '2.0'
info:
  version: '1.0.0'
  title: 'BFF'
  description: Backend For Frontend
schemes:
  - https
security:
  - firebase: []
securityDefinitions: 
  firebase:
    authorizationUrl: ""
    flow: "implicit"
    type: "oauth2"
    x-google-issuer: "https://securetoken.google.com/${PROJECT}"
    x-google-jwks_uri: "https://www.googleapis.com/service_accounts/v1/metadata/x509/securetoken@system.gserviceaccount.com"
    x-google-audiences: ${PROJECT}
paths:
  /test/auth:
    post:
      operationId: testAuth
      summary: Test auth
      produces:
        - application/json
      x-google-backend:
        address: https://${REGION}-${PROJECT}.cloudfunctions.net/auth-test
      responses:
        '200':
          description: 'Response returns user related data from JWT'
  /record/new:
    post:
      operationId: crateRecord
      summary: Create new record
      x-google-backend:
        address: ${RUN_SERVICE_URL}:${RUN_SERVICE_PORT}/new
      produces:
      - application/json
      parameters:
        - in: body
          name: data
          description: Data for new record
          schema:
            $ref: '#/definitions/Record'
      responses:
        '200':
          description: New record data
          schema:
              $ref: '#/definitions/Record'
        '400':
          description: Invalid input data

问题是 API 网关出于某种原因无法调用云 运行 服务,但它可以调用云功能:

            ┍ Client is passing authorization token in header
            |
            |            ┍ Auth is successful and request is forwarded to cloud run 
            |            |
            |            |           ┍ 401 unauthorized to invoke cloud run
            |            |           |
            ↓            ↓           ↓
Client -----------> API Gateway -----X-----> Cloud run service

API 网关服务帐户具有以下相关角色:roles/cloudfunctions.invokerroles/run.invokerroles/iam.serviceAccountUser

运行 服务还具有角色 roles/run.invoker

的网关服务帐户的 IAM 绑定

当我使用 /test/auth 路由时,我可以看到 firebase 身份验证按预期工作,我可以毫无问题地触发云功能,并作为响应来自 x-apigateway-api-userinfo 的云功能 returns 数据正如预期的那样。但是当我使用相同的授权令牌向 运行 服务路由 /record/new 发出请求时,我得到:

www-authenticate: Bearer error="invalid_token" error_description="The access token could not be verified"

401 Unauthorized

Your client does not have permission to the requested URL /new.

我运行不知道可能是什么问题,任何建议都会有所帮助。

使用 Cloud Functions,创建的身份令牌会自动包含正确的受众。当您调用 Cloud 运行 时,情况并非如此,您必须明确提及 Cloud 运行 受众

  /record/new:
    post:
      operationId: crateRecord
      summary: Create new record
      x-google-backend:
        address: ${RUN_SERVICE_URL}:${RUN_SERVICE_PORT}/new
        jwt_audience: ${RUN_SERVICE_URL}

试一试,现在应该可以了。