无法使用服务帐户搜索google drive文件

时间:2018-03-20 05:11:12

标签: c# google-drive-api google-drive-team-drive

我有一个gmail帐户说abc@gmail.com,我已经生成了使用谷歌驱动器搜索API的客户端密码。使用this Sample Code,我能够使用我的控制台应用程序搜索和获取文件。但是这段代码会在本地将令牌保存到驱动器上,因此为了以编程方式传递凭据,我创建了Service Account,如post中所述。

我创建的服务帐户具有以下角色 -

  1. 服务帐户管理员
  2. 服务帐户密钥管理
  3. 服务帐户令牌创建者
  4. 服务帐户用户
  5. 所有者
  6. 但是当我尝试使用服务帐户获取文件时,即使我的abc@gmail.com帐户驱动器中有文件,它也不会返回任何文件。

    这是我的代码 -

    static void Main(string[] args)
    {
        try
        {
            //var service = AuthenticateServiceAccountV2();
            var service = AuthenticateServiceAccountV1(GServiceAccount, "keycredentials.json");
    
            string pageToken = null;
            do
            {
                var request = service.Files.List();
                request.Q = $"name contains 'l'";
                request.Spaces = "drive";
                request.Fields = "nextPageToken, files(id, name, modifiedTime, fileExtension, webViewLink)";
                request.PageToken = pageToken;
                request.PageSize = 5;
                var result = request.Execute();
                foreach (Google.Apis.Drive.v3.Data.File file in result.Files)
                {
    
                    var t = service.Files.Get(file.Id);
                    Console.WriteLine(String.Format("Found file: {0} ({1}) Link for download: {2}", file.Name, file.Id, GenerateUrl(file.Id)));
                }
                pageToken = result.NextPageToken;
            } while (pageToken != null);
            Console.Read();
        }
        catch(Exception ex)
        {
            throw ex;
        }
    }
    static DriveService AuthenticateServiceAccountV1(string ServiceAccountEmail, string KeyFilePath)
    {
        try
        {
            if (string.IsNullOrEmpty(KeyFilePath))
                throw new Exception("Path to the service account credentials file is required.");
            if (!File.Exists(KeyFilePath))
                throw new Exception("The service account credentials file does not exist at: " + KeyFilePath);
            if (string.IsNullOrEmpty(ServiceAccountEmail))
                throw new Exception("ServiceAccountEmail is required.");
            if (Path.GetExtension(KeyFilePath).ToLower() == ".json")
            {
                GoogleCredential credential;
                using (var stream = new FileStream(KeyFilePath, FileMode.Open, FileAccess.Read))
                {
                    credential = GoogleCredential.FromStream(stream)
                         .CreateScoped(Scopes);
                }
                return new DriveService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Drive Service account Authentication Sample",
                });
            }
            else if (Path.GetExtension(KeyFilePath).ToLower() == ".p12")
            {
                var certificate = new X509Certificate2(KeyFilePath, "notasecret", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
                ServiceAccountCredential credential = new ServiceAccountCredential(
                    new ServiceAccountCredential.Initializer(ServiceAccountEmail)
                    {
                        Scopes = Scopes,
                    }.FromCertificate(certificate));
    
                return new DriveService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = ApplicationName
                });
            }
            else
            {
                throw new Exception("Unsupported Service accounts credentials.");
            }
        }
        catch (Exception ex)
        {
            return null;
        }
    }
    

0 个答案:

没有答案