0

I have a gmail account say abc@gmail.com, I have generated a client secret for using google drive search api. With this Sample Code, I was able to search and get files using my console application. But this code, saves the token on to the drive locally, so to pass credentials programmatically I created a Service Account as mentioned in this post.

The service account I created has following roles-

  1. Service Account Admin
  2. Service Account Key Admin
  3. Service Account Token Creator
  4. Service Account User
  5. Owner

But when I try to get files using service account, it returns no files even though I have files in my abc@gmail.com account drive.

Here is my code-

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;
    }
}
Sonali
  • 2,223
  • 6
  • 32
  • 69
  • Where you able to share the files/folder to the service accounts email address as mentioned from your link? – Mr.Rebot Mar 20 '18 at 16:32
  • @Mr.Rebot yes but that does not meet my need as I want to perform searching in logged-in user's drive, in that case it will not be feasible to share every user's drive with service account. – Sonali Mar 21 '18 at 07:32

0 Answers0