.Net中Google服务账号凭证无效错误排查求助
Google服务账号凭证无效问题排查与修复
问题描述
我正尝试通过.Net代码认证Google API,调用Google预订的实时更新接口,但始终收到错误提示:"JSON data does not represent a valid service account credential",且自定义的PatchAsync方法从未执行到。密钥是新生成并已复制到项目中,需要解决该凭证无效问题。
代码示例
[STAThread] public static async Task UpdateBookingNotificationAsync(string bookingId, object payload) { try { string[] scopes = { "https://www.googleapis.com/auth/mapsbooking" }; GoogleCredential credential; using (var stream = new FileStream(JSON_KEY_FULL_PATH, FileMode.Open, FileAccess.Read)) { credential = GoogleCredential.FromStream(stream).CreateScoped(scopes); System.IO.File.WriteAllText("prova.txt", "dio"); } Oauth2Service baseClient = new Oauth2Service(new BaseClientService.Initializer() { HttpClientInitializer = credential }); ConfigurableHttpClient httpClient = baseClient.HttpClient; Dictionary<string, string> values = new Dictionary<string, string> { { "name", String.Format("partners/{0}/bookings/{1}", PARTNER_ID, bookingId) }, { "payload", payload.ToString() } }; FormUrlEncodedContent body = new FormUrlEncodedContent(values); HttpResponseMessage responseString = await httpClient.PatchAsync( String.Format("{0}/v1alpha/notification/partners/{1}/bookings/{2}?updateMask={3}", ENDPOINT, PARTNER_ID, bookingId, payload), body, CancellationToken.None).ConfigureAwait(false); } catch (Exception ex) { Debug.WriteLine(ex.Message); throw new Exception(ex.Message); } }
服务账号JSON示例
{ "type": "service_account", "project_id": "rest-c-012345", "private_key_id": "****", "private_key": "-----BEGIN PRIVATE KEY----- **** \n-----END PRIVATE KEY-----\n", "client_email": "****@rest-c-012345.iam.gserviceaccount.com", "client_id": "00000000000000000000", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/****@rest-c-012345.iam.gserviceaccount.com" }
排查与修复步骤
1. 检查服务账号JSON完整性
- 重点校验
private_key字段:原JSON中的密钥格式存在问题,实际密钥应为连续的多行字符串,不能有多余空格。正确格式示例:"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC...\n...\n-----END PRIVATE KEY-----\n" - 确认所有必填字段无缺失:
type必须为"service_account",project_id、client_email、private_key、token_uri等核心字段不能被错误修改或遗漏。
2. 验证文件读取路径与权限
- 确保
JSON_KEY_FULL_PATH指向的文件路径正确,且程序拥有该文件的读取权限。可添加日志输出路径值,确认路径是否正确。
3. 调整凭证初始化方式
- 尝试显式指定服务账号类型初始化,避免自动识别异常:
credential = ServiceAccountCredential.FromServiceAccountData(stream).CreateScoped(scopes); - 也可通过环境变量
GOOGLE_APPLICATION_CREDENTIALS指向JSON文件,使用GoogleCredential.GetApplicationDefault()测试凭证是否能正常加载。
4. 检查NuGet依赖版本
- 确保
Google.Apis、Google.Apis.Auth等相关NuGet包为最新稳定版,旧版本可能存在凭证解析bug。
5. 修复代码中其他潜在问题
- 避免使用
Oauth2Service获取HttpClient,应直接构建适配Google Maps Booking API的客户端,或通过凭证生成访问令牌后直接调用接口。 payload.ToString()无法正确序列化对象为API所需的JSON格式,需使用Newtonsoft.Json或System.Text.Json将对象序列化为JSON字符串。updateMask参数应为需要更新的字段列表(如"status,notes"),而非直接传入payload对象。
内容的提问来源于stack exchange,提问作者IlJeko
相关产品推荐
相关产品推荐

