如何限制GCP API Gateway仅接受特定域名请求以保障安全?
解决方案:在GCP API Gateway层面限制特定IP访问
要实现仅允许你的VPS调用API Gateway且不触发Cloud Function计费,核心是在网关层直接拦截非授权请求,避免请求到达后端函数。以下是两种可行方案:
方案一:在Swagger配置中添加IP白名单(推荐)
GCP API Gateway支持通过Swagger配置的securityDefinitions直接设置IP访问限制,所有不符合规则的请求会被网关直接拒绝,不会转发到Cloud Function。
修改后的Swagger配置示例
swagger: '2.0' info: title: api-gateway description: API Gateway version: 1.0.0 schemes: - https produces: - application/json # 新增安全定义:IP白名单限制 securityDefinitions: ip-whitelist: type: "ipAddress" description: "仅允许指定VPS IP访问" ipAddress: "1.2.3.4/32" # 替换为你的VPS公网IP(CIDR格式,单个IP用/32) paths: /v1/hello: get: summary: Hi Service operationId: hello-v1 # 启用IP白名单限制 security: - ip-whitelist: [] x-google-backend: address: <CLOUD_RUN_URL> responses: '200': description: OK '403': description: 禁止访问(非授权IP)
操作步骤
- 获取你的VPS公网IP(可在VPS上执行
curl ifconfig.me获取) - 将配置中的
1.2.3.4/32替换为你的VPS IP(多个IP可写成["1.2.3.4/32", "5.6.7.8/32"]) - 重新部署API Gateway配置:
gcloud api-gateway api-configs create [CONFIG_NAME] --api=[API_NAME] --openapi-spec=[PATH_TO_YOUR_YAML_FILE] --project=[PROJECT_ID] gcloud api-gateway gateways update [GATEWAY_NAME] --api-config=[CONFIG_NAME] --location=[REGION] --project=[PROJECT_ID]
方案二:集成Cloud Armor安全策略
如果需要更灵活的访问控制(比如后续无需重新部署网关即可修改IP规则),可以将Cloud Armor与API Gateway集成。
操作步骤
- 创建Cloud Armor安全策略:
gcloud compute security-policies create vps-only-policy --description="仅允许VPS IP访问API Gateway" --project=[PROJECT_ID] - 添加允许VPS IP的规则(优先级数字越小,规则越优先):
gcloud compute security-policies rules create 100 \ --security-policy vps-only-policy \ --action allow \ --src-ip-ranges 1.2.3.4/32 \ --description="允许VPS IP访问" \ --project=[PROJECT_ID] - 添加默认拒绝所有其他请求的规则:
gcloud compute security-policies rules create 200 \ --security-policy vps-only-policy \ --action deny-403 \ --description="拒绝所有非授权IP" \ --project=[PROJECT_ID] - 将安全策略关联到API Gateway:
gcloud api-gateway gateways update [GATEWAY_NAME] \ --security-policy vps-only-policy \ --location=[REGION] \ --project=[PROJECT_ID]
关键说明
- 两种方案都是在API Gateway层面拦截请求,不会触发Cloud Function运行,完全避免了不必要的计费。
- 若你的VPS使用动态IP,可结合DNS解析获取IP范围,但固定IP场景下直接使用IP白名单最可靠。
- 不要使用CORS策略:CORS是浏览器端的限制,且OPTIONS预请求会触发Cloud Function执行,不符合你的需求。
内容的提问来源于stack exchange,提问作者ChristianOConnor
相关产品推荐
相关产品推荐

