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

如何在GCP API Gateway中通过gRPC实现自定义认证并转发请求至后端

GCP API Gateway实现gRPC请求前置自定义认证(Cloud Run)方案

核心思路

API Gateway支持通过**自定义认证器(Custom Authenticator)**对gRPC请求做前置校验,校验逻辑托管在你的Cloud Run认证服务中。认证通过后,API Gateway会将用户信息注入请求上下文,再转发到目标业务Cloud Run服务。

步骤1:调整认证服务的gRPC接口

你的Cloud Run认证服务需要实现符合API Gateway要求的gRPC认证方法:

  • 从gRPC请求的**元数据(Metadata)**中提取authorization(token)和x-session-id字段
  • 执行token有效性校验、session ID关联用户的逻辑
  • 校验通过后返回包含用户标识(如user_id、role)的结构化数据;校验失败则返回UNAUTHENTICATED等标准gRPC错误码

步骤2:配置API Gateway的gRPC API定义

在你的gRPC服务.proto文件中,添加认证规则指定自定义认证服务的地址和调用规则:

import "google/api/annotations.proto";
import "google/api/auth.proto";

service BusinessService {
  // 配置自定义认证器
  option (google.api.auth) = {
    custom_auth: {
      // 认证服务的gRPC端点(Cloud Run需启用HTTP/2)
      url: "https://your-auth-service-run-id-uc.a.run.app/grpc.auth.v1.Authenticator/Authenticate"
      // 提取token的头部字段
      authorization_header: "Authorization"
      // 额外传递给认证服务的头部
      custom_headers: ["x-session-id"]
    }
  };

  rpc DoBusiness(BusinessRequest) returns (BusinessResponse) {
    option (google.api.http) = {
      post: "/v1/business"
      body: "*"
    };
  }
}

步骤3:编译proto并部署API Gateway

  1. 使用protoc编译proto文件,生成API Gateway兼容的配置:
protoc --grpc-gateway_out=logtostderr=true:. \
       --google_api_out=logtostderr=true:. \
       --proto_path=. your-service.proto
  1. 将编译后的配置文件上传至GCS,再通过gcloud命令部署API Gateway:
gcloud api-gateway api-configs create your-config \
  --api=your-api \
  --grpc-files=gcs://your-bucket/your-service.pb \
  --backend-auth-service-account=your-service-account@project-id.iam.gserviceaccount.com
  • backend-auth-service-account需拥有Cloud Run Invoker权限,能调用认证服务和业务服务

步骤4:在业务服务中获取用户信息

认证通过后,API Gateway会将认证服务返回的用户信息注入请求元数据,业务服务可通过gRPC请求的Metadata读取,比如x-user-id、x-user-role等自定义字段(需在认证服务响应中定义)

关键注意事项

  • 部署Cloud Run认证服务时需启用HTTP/2,添加--use-http2参数
  • 认证服务的响应需包含status和claims结构,claims字段存放用户信息
  • 确保API Gateway的服务账号拥有调用目标Cloud Run服务的权限

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 00:53:31