如何通过C#客户端库完成Google Routes API身份验证
如何通过C#客户端库完成Google Routes API身份验证
嘿,我之前刚踩过Google Routes API在C#里身份验证的坑,整理了几个靠谱的实现方法,给你参考下~
最常用的两种服务账号验证方式
方法一:直接加载服务账号密钥文件
这是本地开发和自建后台服务最常用的方式,步骤很清晰:
- 先去Google Cloud控制台创建对应服务账号,下载生成的JSON密钥文件
- 把密钥文件放到项目目录里,右键设置它的“复制到输出目录”属性为「如果较新则复制」(避免编译后找不到文件)
- 代码里这样初始化客户端:
using Google.Cloud.Routes.V1; using Google.Apis.Auth.OAuth2; public async Task ComputeAuthenticatedRoutesAsync() { // 加载服务账号密钥,并指定API所需的权限范围 var credentials = GoogleCredential.FromFile("your-service-account-key.json") .CreateScoped(RoutesClient.DefaultScopes); // 用验证凭据创建Routes客户端 var routesClient = await RoutesClient.CreateAsync(credentials); // 接下来就可以正常构造请求调用API了 var request = new ComputeRoutesRequest { Origin = new Waypoint { Address = "北京天安门" }, Destination = new Waypoint { Address = "北京故宫" }, TravelMode = RouteTravelMode.Drive }; var response = await routesClient.ComputeRoutesAsync(request); // 处理返回的路线数据... }
⚠️ 注意:密钥文件一定要妥善保管,绝对不能提交到公开的代码仓库里!
方法二:通过环境变量指定密钥(适合云部署场景)
如果是部署到GCP的云函数、App Engine这类托管服务,或者本地不想硬编码密钥文件名,推荐用环境变量的方式:
- 设置环境变量
GOOGLE_APPLICATION_CREDENTIALS,值为密钥文件的绝对路径- Windows命令行:
set GOOGLE_APPLICATION_CREDENTIALS=C:\path\to\your-key.json - Linux/macOS终端:
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/your-key.json
- Windows命令行:
- 代码里就可以简化成自动读取凭据:
using Google.Cloud.Routes.V1; public async Task ComputeRoutesWithEnvCredentialsAsync() { // 客户端会自动读取环境变量中的凭据信息 var routesClient = await RoutesClient.CreateAsync(); // 构造请求并调用API var request = new ComputeRoutesRequest { Origin = new Waypoint { Address = "上海外滩" }, Destination = new Waypoint { Address = "上海东方明珠" } }; var response = await routesClient.ComputeRoutesAsync(request); }
在GCP的托管服务中,甚至不需要手动设置环境变量,服务会自动使用当前资源绑定的服务账号凭据,非常省心。
小众但有用的用户授权方式
如果你的应用需要让用户授权访问他们的个人路线数据(比如桌面应用场景),可以用OAuth2用户凭据:
using Google.Apis.Auth.OAuth2; using Google.Cloud.Routes.V1; using System.IO; using System.Threading; public async Task ComputeRoutesWithUserCredentialsAsync() { // 加载OAuth客户端密钥(从Google Cloud控制台下载的client_secrets.json) UserCredential credential; using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read)) { credential = await GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, new[] { RoutesClient.DefaultScopes[0] }, "current-user", CancellationToken.None); } var routesClient = await RoutesClient.CreateAsync(credential); // 后续请求逻辑和之前一致... }
这种方式需要先创建OAuth客户端ID,适合需要用户交互的场景。
必看的注意事项
- 不管用哪种方式,都要确保你的服务账号/用户已经被授予了
Routes Viewer(或更高权限),去Google Cloud控制台的IAM页面配置权限,不然会收到权限不足的错误 - 本地开发时,也可以用
gcloud auth application-default login命令登录,客户端会自动使用gcli的默认凭据,省去配置文件的麻烦
内容来源于stack exchange
相关产品推荐
相关产品推荐

