You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何限制Google Endpoint URL仅允许特定服务账号的Compute Engine访问

确保特定服务账号的GCE实例访问Google Endpoints API的解决方案

我之前也碰到过类似的问题——光加securityDefinitions确实不够,还得把认证规则绑定到端点,同时做好GCE实例和服务账号的配置。下面一步步来解决:

1. 完善OpenAPI规范的认证配置

首先,你需要在OpenAPI文件里不仅定义securityDefinitions,还要在需要保护的端点上明确启用认证,并且配置正确的服务账号验证规则:

# 定义服务账号认证规则
securityDefinitions:
  restricted_service_account:
    type: "google_id_token"
    authorizationUrl: ""
    flow: "implicit"
    # 替换成你要允许的服务账号邮箱
    x-google-issuer: "allowed-sa@your-project-id.iam.gserviceaccount.com"
    # 对应服务账号的公钥地址(格式固定,替换邮箱即可)
    x-google-jwks_uri: "https://www.googleapis.com/service_accounts/v1/metadata/x509/allowed-sa@your-project-id.iam.gserviceaccount.com"
    # 替换成你的Endpoints服务域名(格式:{service-name}.endpoints.{project-id}.cloud.goog)
    x-google-audiences: "your-endpoints-service.endpoints.your-project-id.cloud.goog"

# 在需要保护的端点上启用认证
paths:
  /your-protected-endpoint:
    get:
      # 绑定上面定义的认证规则
      security:
        - restricted_service_account: []
      summary: "受保护的API端点"
      responses:
        200:
          description: "成功响应"

关键注意点:

  • x-google-issuer必须是你要授权的服务账号完整邮箱
  • x-google-audiences必须和你的Endpoints服务域名完全一致
  • 每个需要保护的端点都要添加security字段,否则Endpoints不会强制认证

2. 重新部署更新后的OpenAPI配置

修改完配置后,一定要重新部署到Endpoints,否则新的认证规则不会生效:

gcloud endpoints services deploy your-openapi-file.yaml

部署完成后,可以用gcloud endpoints services describe your-endpoints-service.endpoints.your-project-id.cloud.goog检查配置是否已更新。

3. 配置GCE实例使用指定服务账号

确保你的Compute Engine实例已经绑定了上面配置的allowed-sa@your-project-id.iam.gserviceaccount.com服务账号:

  • 创建/编辑GCE实例时,在"服务账号"选项中选择目标服务账号
  • 确保该服务账号拥有roles/compute.serviceAccountUser角色(允许GCE实例使用该账号)

4. 在GCE实例中携带正确的Token访问API

GCE实例可以通过元数据服务器获取针对Endpoints的ID Token,请求时携带这个Token即可通过认证:

# 获取ID Token(替换为你的Endpoints服务域名)
TOKEN=$(curl -H "Metadata-Flavor: Google" \
  "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity?audience=your-endpoints-service.endpoints.your-project-id.cloud.goog")

# 调用API时携带Token
curl -H "Authorization: Bearer $TOKEN" \
  https://your-endpoints-service.endpoints.your-project-id.cloud.goog/your-protected-endpoint

5. 验证未授权访问被拒绝

测试一下:如果从本地或者其他未绑定指定服务账号的实例访问该端点,应该会收到401 Unauthorized响应,这就说明认证规则生效了。

常见排查点

  • 确认端点的security字段没有遗漏——这是最容易犯的错误,只定义securityDefinitions但不绑定到端点等于没开认证
  • 检查x-google-issuer和x-google-audiences的拼写是否完全正确,任何拼写错误都会导致Token验证失败
  • 确认GCE实例的服务账号和OpenAPI中配置的完全一致,包括邮箱后缀

内容的提问来源于stack exchange,提问作者pythonhmmm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:21:36