使用 API 密钥

本页介绍了如何在 API Gateway 中使用 API 密钥。

API 密钥是一个字符串,用于标识Google Cloud 项目,以实现配额、结算和监控的目的。开发者在 Google Cloud 控制台的项目中生成 API 密钥。然后,他们会将该密钥作为查询参数嵌入到对 API 的每次调用中或嵌入到请求标头中。

如果您在 API 配置中指定 API 密钥要求,API Gateway 会使用 API 密钥来查找关联的 Google Cloud 项目。除非 API 密钥是在您的 Google Cloud 项目或已启用 API 的其他Google Cloud 项目中生成的,否则 API Gateway 将拒绝请求。

如需创建 API 密钥或查看 Google Cloud 项目内已有的 API 密钥,请前往 API 和服务 > 凭据页面。

进入“凭据”页面

使用 API 密钥

要使用配额之类的 API Gateway 功能,您可以传入 API 密钥,以便 API Gateway 可以识别与客户端应用关联的 Google Cloud 项目。

为 API Gateway 配置 API 密钥身份验证

如需使用 API 密钥保护对网关的访问,请执行以下操作:

  1. 为您的服务启用 API 密钥支持。 输入以下命令,其中:
    • MANAGED_SERVICE_NAME 指定您在部署 API 时创建的代管式服务的名称。这可以通过 gcloud api-gateway apis describe 命令列出的代管式服务属性查看。
    • PROJECT_ID 指定 Google Cloud 项目的名称。
    gcloud services enable MANAGED_SERVICE_NAME.apigateway.PROJECT_ID.cloud.goog
    例如:
    gcloud services enable my-api-123abc456def1.apigateway.my-project.cloud.goog
  2. 修改用于创建 API 配置的 OpenAPI 规范,以包括对所有流量强制执行 API 密钥验证安全政策的说明。 添加 security 类型和 securityDefinitionssecuritySchemes,如下所示:

    OpenAPI 2.0

      # openapi2-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
            x-google-backend:
              address: https://GCP_REGION-PROJECT_ID.cloudfunctions.net/helloGET
            security:
            - api_key: []
            responses:
              '200':
                description: A successful response
                schema:
                  type: string
      securityDefinitions:
        # This section configures basic authentication with an API key.
        api_key:
          type: "apiKey"
          name: "key"
          in: "query"

    securityDefinition 将 API 配置为要求请求访问规范中定义的所有路径时作为名为 key 的查询参数传递的 API 密钥。

    OpenAPI 3.x

    # openapi-functions.yaml
    openapi: 3.0.4
    info:
      title: API_ID optional-string
      description: Sample API on API Gateway with a Google Cloud Functions backend
      version: 1.0.0
    # Define reusable components in x-google-api-management
    x-google-api-management:
      backend:
        functions_backend:
          address: https://GATEWAY_LOCATION-PROJECT_ID.cloudfunctions.net/helloGET
          pathTranslation: APPEND_PATH_TO_ADDRESS
          protocol: "http/1.1"
    # Apply the backend configuration by referencing it by name. Set at the root so this applies to all operations unless overridden.
    x-google-backend: functions_backend
    components:
    # This section configures basic authentication with an API key.
      securitySchemes:
        google_api_key:
          type: apiKey
          name: x-api-key
          in: header
    security:
      - google_api_key: []
    paths:
      /hello:
        get:
          summary: Greet a user
          operationId: hello
          responses:
            '200':
              description: A successful response
              content:
                application/json:
                  schema:
                    type: string

    securitySchemes 将 API 配置为要求请求访问规范中定义的所有路径时作为名为 key 的查询参数传递的 API 密钥。

  3. 使用以下命令,使用修改后的 OpenAPI 说明创建新的 API 配置:
    gcloud api-gateway api-configs create NEW_CONFIG_ID \
    --api=API_ID --openapi-spec=NEW_API_DEFINITION \
    --project=PROJECT_ID --backend-auth-service-account=SERVICE_ACCOUNT_EMAIL
    例如:
    gcloud api-gateway api-configs create my-config-key \
      --api=my-api --openapi-spec=openapi-functions.yaml \
      --project=my-project --backend-auth-service-account=0000000000000compute@developer.gserviceaccount.com
  4. 运行以下命令,使用新的 API 配置更新现有网关
    gcloud api-gateway gateways update GATEWAY_ID \
      --api=API_ID --api-config=NEW_CONFIG_ID \
      --location=GATEWAY_LOCATION --project=PROJECT_ID
    例如:
    gcloud api-gateway gateways update my-gateway \
      --api=my-api --api-config=my-config-key \
      --location=us-central1 --project=my-project

限制 API 密钥

默认情况下,API 密钥不受限制,这使得它们容易遭到未经授权的使用。尽可能添加 API 限制。 API 限制用于指定可以使用 API 密钥调用哪些 API。生产应用使用的所有 API 密钥都应具有 API 限制。

如需添加 API 限制,请执行以下操作:

  1. 找到 API 配置中记录的 API 标题。在以下示例中,API 标题为 My Example Config

    OpenAPI 2.0

    # openapi.yaml
    swagger: '2.0'
    info:
      title: My Example Config
      description: Sample API on API Gateway
      version: 1.0.0
    ...

    OpenAPI 3.x

    # openapi.yaml
    openapi: 3.0.4
    info:
      title: My Example Config
      description: Sample API on API Gateway
      version: 1.0.0
    ...

  2. 在 Google Cloud 控制台中,前往 API 和服务 > 凭据页面。

    进入“凭据”页面

  3. 选择要用于 API 的 API 密钥的名称。

  4. 在 API 密钥详情页面的 API 限制部分中,点击限制密钥

  5. 从可用 API 的下拉列表中选择您的 API 密钥将用于访问的 API。例如,选择 My Example Config

  6. 点击保存

您的限制应该很快就会生效。