快速入门:使用 Google Cloud 控制台保护传入服务的流量

本页面介绍如何在 API Gateway 上部署 API 以保护流向后端服务的流量。

请按照以下步骤使用 Google Cloud 控制台部署新的 API 以访问 Cloud Run functions 上的后端服务。本快速入门还介绍了如何使用 API 密钥保护您的后端免遭未经授权的访问。

准备工作

  1. 在 Google Cloud 控制台中,前往 API Gateway 页面。

    前往 API Gateway

  2. API Gateway 要求您启用以下 Google 服务:

    名称 标题
    apigateway.googleapis.com API Gateway API
    servicemanagement.googleapis.com Service Management API
    servicecontrol.googleapis.com Service Control API

    如果您之前没有为所选项目启用这些服务,则系统会提示您执行此操作。

  3. 确认您的项目已启用结算功能。

    了解如何启用结算功能

部署 API 后端

API Gateway 位于已部署后端服务的前面,负责处理所有传入请求。在本快速入门中,API Gateway 会将传入的调用路由到名为 helloGET 的 Cloud Run 函数后端,该后端包含如下所示的 Node.js 函数。

const functions = require('@google-cloud/functions-framework');

// Register an HTTP function with the Functions Framework that will be executed
// when you make an HTTP request to the deployed function's endpoint.
functions.http('helloGET', (req, res) => {
  res.send('Hello World!');
});

按照快速入门:使用 Google Cloud CLI 中的步骤下载示例 Cloud Run 函数代码并部署 Cloud Run 函数后端服务。

按照快速入门:使用 Google Cloud CLI 中的步骤下载示例 Cloud Run 函数代码并部署 Cloud Run 函数后端服务。您的管理员需要按照此快速入门中的说明,向您的账号和 Cloud Build 服务账号授予其他角色。

复制 Cloud Run 函数部署完成后显示的服务网址。在下一步中创建 API 配置时,您需要使用此值。

创建 API 配置

API Gateway 使用 API 配置将调用路由到后端服务。您可以使用包含专用扩展程序的 OpenAPI 规范来定义所选的 API Gateway 行为。如需详细了解支持的 OpenAPI 扩展程序,请参阅以下内容:

本快速入门的 OpenAPI 规范包含针对 Cloud Run 函数后端的路由指令:

OpenAPI 2.0

# openapi-functions.yaml
swagger: '2.0'
info:
  title: API_ID optional-string
  description: Sample API on API Gateway with a Google Cloud Functions backend
  version: 1.0.0
schemes:
  - https
produces:
  - application/json
paths:
  /hello:
    get:
      summary: Greet a user
      operationId: hello