簡體   English   中英

C# Google Drive:允許用戶讀取我的驅動器

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

我似乎無法為我想要做的事情找到明確的答案。

我有一個 Google Drive,我在其中維護一組文件夾和文件。 (不是我的私人驅動器,而是專門為此目的創建的驅動器。)我正在編寫一個程序,該程序將下載自用戶上次檢查以來更改的任何文件夾/文件。 文件位於共享文件夾中(任何有鏈接的人都可以查看)

我如何讓用戶(通過我的程序)讀取我的 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();

我建議您考慮使用服務帳戶。 服務帳戶就像虛擬用戶。 如果您授予服務帳戶訪問這些文件夾的權限,它將有權訪問它們以執行您想要的任何操作。 沒有用戶需要登錄和驗證訪問。 服務帳戶是預先授權的。

例子

/// <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 初學者服務帳戶開發

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM