如何通过GCP API Gateway限制仅指定IP访问Google App Engine
在GCP API网关的OpenAPI YAML中配置IP白名单限制
要实现仅允许特定IP访问API网关,你需要在现有OpenAPI配置中添加IP白名单限制规则,具体修改如下:
修改后的完整OpenAPI YAML配置
# openapi2-appengine.yaml swagger: '2.0' info: title: rest-api description: API Gateway version: 1.0.0 schemes: - http - https produces: - text/html - application/json x-google-backend: address: https://gcp.appspot.com/ jwt_audience: 12345678 # 新增:定义IP限制的安全规则 securityDefinitions: ip_restriction: type: "apiKey" name: "X-Forwarded-For" in: "header" x-google-restrictions: allowedIps: - "192.168.1.0/24" # 替换为你的白名单IP/网段 - "203.0.113.5" # 单个IP示例 # 新增:全局启用IP限制(也可在单个接口单独配置) security: - ip_restriction: [] paths: /get_data: get: summary: GET data description: To get data produces: - application/json operationId: Data # 若不需要全局限制,可在此处单独添加security规则覆盖全局 # security: # - ip_restriction: [] responses: 200: description: A successful response 403: description: Access forbidden
关键配置说明
- securityDefinitions:定义名为
ip_restriction的安全规则,通过检查请求头X-Forwarded-For(GCP API网关会将客户端真实IP写入该头)验证IP是否在白名单内。 - allowedIps:填写需要放行的IP地址或CIDR网段,多个条目以数组形式列出。
- security:全局配置该规则时,会作用于所有接口;若仅需给特定接口加限制,将
security块移到对应接口的配置下即可。
配置完成后重新部署API网关即可生效,非白名单IP的请求会直接返回403 Forbidden。
内容的提问来源于stack exchange,提问作者Cloude
相关产品推荐
相关产品推荐

