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

使用C#调用Google Drive API v1.68遇身份验证无效错误求助

解决Google Drive API服务账户认证Unauthorized错误

问题出在服务账户凭证未指定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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 23:52:46