C# Google 驱动器:允许用户读取我的驱动器

C# Google Drive : Allow users read access to my drive

我似乎无法找到我想做的事情的明确答案。

我有一个 Google 驱动器,我在其中维护一组文件夹和文件。 (不是我的私人驱动器,而是专门为此目的创建的驱动器。)我正在编写一个程序,它将下载自用户上次检查以来更改的任何文件夹/文件。这些文件位于共享的文件夹中(拥有 link 的任何人都可以查看)

如何让用户(通过我的程序)读取我的 Google 驱动器?

我能找到的所有 OAuth2 / client_secret.json 示例允许我请求用户访问 THEIR 驱动器的权限。这不是我想要的。

UserCredential credential;
using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{    
    credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
        GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None);
}

_driveService = new DriveService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credential,
    ApplicationName = ApplicationName
});

FilesResource.ListRequest request = _driveService.Files.List();
FileList files = await request.ExecuteAsync();

我尝试使用 Api 键方式,但随后出现错误提示用户需要登录。

_driveService = new DriveService(new BaseClientService.Initializer()
{
    ApiKey = "[MyApiKey]",
    ApplicationName = ApplicationName
});

FilesResource.ListRequest request = _driveService.Files.List();
FileList files = await request.ExecuteAsync();

我建议您考虑使用服务帐户。服务帐户就像虚拟用户。如果您授予服务帐户对这些文件夹的访问权限,它将有权访问这些文件夹以执行您希望对它们执行的任何操作。没有用户需要登录和验证访问权限。服务帐户是预授权的。

示例

/// <summary>
    /// Authenticating to Google using a Service account
    /// Documentation: https://developers.google.com/accounts/docs/OAuth2#serviceaccount
    /// </summary>
    /// <param name="serviceAccountEmail">From Google Developer console https://console.developers.google.com</param>
    /// <param name="serviceAccountCredentialFilePath">Location of the .p12 or Json Service account key file downloaded from Google Developer console https://console.developers.google.com</param>
    /// <returns>AnalyticsService used to make requests against the Analytics API</returns>
    public static DriveService AuthenticateServiceAccount(string serviceAccountEmail, string serviceAccountCredentialFilePath, string[] scopes)
    {
        try
        {
            if (string.IsNullOrEmpty(serviceAccountCredentialFilePath))
                throw new Exception("Path to the service account credentials file is required.");
            if (!File.Exists(serviceAccountCredentialFilePath))
                throw new Exception("The service account credentials file does not exist at: " + serviceAccountCredentialFilePath);
            if (string.IsNullOrEmpty(serviceAccountEmail))
                throw new Exception("ServiceAccountEmail is required.");                

            // For Json file
            if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".json")
            {
                GoogleCredential credential;
                using (var stream = new FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read))
                {
                    credential = GoogleCredential.FromStream(stream)
                         .CreateScoped(scopes);
                }

                // Create the  Analytics service.
                return new DriveService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Drive Service account Authentication Sample",
                });
            }
            else if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".p12")
            {   // If its a P12 file

                var certificate = new X509Certificate2(serviceAccountCredentialFilePath, "notasecret", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
                var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
                {
                    Scopes = scopes
                }.FromCertificate(certificate));

                // Create the  Drive service.
                return new DriveService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Drive Authentication Sample",
                });
            }
            else
            {
                throw new Exception("Unsupported Service accounts credentials.");
            }

        }
        catch (Exception ex)
        {                
            throw new Exception("CreateServiceAccountDriveFailed", ex);
        }
    }
}

从我的示例项目中提取的代码 serviceaccount.cs i also have a post on how service accounts work Google development for beginners service account