C#Google云端硬盘:允许用户读取我的硬盘的访问权限

时间:2018-02-12 14:50:02

标签: c# google-api google-drive-api google-oauth google-api-dotnet-client

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

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

如何向用户(通过我的程序)提供对Google云端硬盘的读取权限?

我能找到的所有OAuth2 / client_secret.json个样本都允许我向用户请求访问他们驱动器的权限。这不是我想要的。

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();

1 个答案:

答案 0 :(得分:1)

我建议您考虑使用服务帐户。服务帐户就像虚拟用户。如果您授予服务帐户对这些文件夹的访问权限,则它将有权访问您随意执行的操作。没有用户需要登录并验证访问权限。服务帐户已预先授权。

示例

/// <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中删除的代码我还有一篇关于服务帐户如何工作的帖子Google development for beginners service account

相关问题