迁移.NET代码至新机器后遭遇Google Sheets OAuth2认证错误
Google Sheets API 401 无效凭证问题排查
问题背景
- 一套稳定运行3年的.NET代码,用于访问共享Google Sheet;原机器硬盘损坏后,从备份恢复代码到新机器,运行时出现401认证错误
- 多次通过gcloud CLI为服务账号完成OAuth 2.0授权,登录了关联应用的正确账号,但改用CLI生成的凭证路径后出现范围错误;原JSON凭证在旧机器上仍可正常使用
错误信息
Google.Apis.Requests.RequestError Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. [401] Errors [ Message[Invalid Credentials] Location[Authorization - header] Reason[authError] Domain[global] ]
相关代码片段
Dim _scopes As String() = {SheetsService.Scope.Spreadsheets} Dim _applicationName As String = "xxx" Dim _spreadsheetId As String = "xxx" Dim _sheetsService As SheetsService Dim credential As GoogleCredential Dim range As String = "Data!A1:CT" credential = GoogleCredential.FromJson(DecryptData(System.IO.File.ReadAllText(System.Windows.Forms.Application.StartupPath & "\1.json"))) Dim bIntializer As New BaseClientService.Initializer() bIntializer.HttpClientInitializer = credential bIntializer.ApplicationName = _applicationName _sheetsService = New SheetsService(bIntializer) Dim Request As SpreadsheetsResource.ValuesResource.GetRequest = _sheetsService.Spreadsheets.Values.Get(_spreadsheetId, range) Dim Response As ValueRange = Request.Execute()
排查与解决方案
- 检查凭证解密逻辑:代码中使用
DecryptData处理凭证文件,新机器可能缺失解密依赖的密钥或环境变量,导致解密后的JSON无效。可临时注释解密步骤,直接读取未加密的原始凭证测试,确认是否为解密环节问题。 - 确认服务账号共享权限:原凭证对应的服务账号邮箱,需确保已被添加为目标Google Sheet的共享用户(权限设为编辑器/查看者);若使用新生成的服务账号凭证,必须重新为该账号授权共享Sheet。
- 修正gcloud CLI授权范围:改用CLI凭证出现范围错误,说明授权时指定的scope与代码中
SheetsService.Scope.Spreadsheets不匹配。执行授权时明确指定正确scope:
同时代码中改用默认凭证加载方式:gcloud auth application-default login --scopes=https://www.googleapis.com/auth/spreadsheetscredential = GoogleCredential.GetApplicationDefault() - 验证凭证文件有效性:将旧机器上可用的未加密凭证复制到新机器,直接读取测试,排除文件损坏或路径错误;检查
Application.StartupPath在新机器上的实际路径,确保能找到1.json文件。 - 统一依赖库版本:新机器上的Google.Apis系列NuGet包版本可能与旧机器不一致,还原旧机器使用的精确版本,避免版本兼容问题。
内容的提问来源于stack exchange,提问作者user246181
相关产品推荐
相关产品推荐

