使用C#调用Google Drive API v1.68遇身份验证无效错误求助
问题出在服务账户凭证未指定Google Drive API的权限作用域,导致无法生成有效的访问令牌。以下是修正后的完整代码:
using Google.Apis.Auth.OAuth2; using Google.Apis.Drive.v3; using Google.Apis.Services; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; public class GoogleDriveService { public struct FileInfo { public string id; public string name; public string mimeType; } private readonly DriveService _driveService; public GoogleDriveService(string serviceAccountJsonPath, string applicationName) { using (var stream = new FileStream(serviceAccountJsonPath, FileMode.Open, FileAccess.Read)) { // 关键修改:添加Drive API只读作用域 var initializer = new ServiceAccountCredential.Initializer( ServiceAccountCredential.FromServiceAccountData(stream).Id) { Scopes = new[] { DriveService.Scope.DriveReadonly }, User = null // 服务账户模式下留空,若要模拟域内用户需填写对应邮箱 }; var serviceAccountCredential = new ServiceAccountCredential(initializer.FromServiceAccountData(stream)); _driveService = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = serviceAccountCredential, ApplicationName = applicationName }); } } public async Task<List<FileInfo>> ListFolderContents(string folderId) { var request = _driveService.Files.List(); request.Q = $"parents = '{folderId}'"; request.Fields = "nextPageToken, files(id, name, mimeType)"; var files = new List<Google.Apis.Drive.v3.Data.File>(); do { var response = await request.ExecuteAsync(); files.AddRange(response.Files); request.PageToken = response.NextPageToken; } while (!string.IsNullOrEmpty(request.PageToken)); var fileInfoList = new List<FileInfo>(); foreach (var file in files) { fileInfoList.Add(new FileInfo() { id = file.Id, name = file.Name, mimeType = file.MimeType }); } return fileInfoList; } }
关键修改说明
- 在创建
ServiceAccountCredential时,明确指定了DriveService.Scope.DriveReadonly作用域,这是服务账户访问Drive读取权限必须声明的范围 - 若需要写入权限,可改用
DriveService.Scope.Drive作用域,需确保服务账户对应文件夹有写入权限 - 若要模拟G Suite域内用户访问,可在
Initializer的User字段填写对应域用户邮箱
额外确认步骤
再次确认目标Google Drive文件夹已共享给服务账户的邮箱地址,并授予查看者权限。
内容的提问来源于stack exchange,提问作者Thomas O'Dell
相关产品推荐
相关产品推荐

