簡體   English   中英

Google Drive API IAuthenticator

[英]Google Drive API IAuthenticator

我正在嘗試將ASP.NET C#應用程序與Google Drive API集成在一起。 我們已成功將文檔以pdf格式存儲到我們的驅動器存儲帳戶中,但是現在我們正在嘗試檢索和下載文件。

我們打了電話,它給了我們數據。 我的問題是,它給了我幾個下載鏈接,並且每個鏈接(當用於檢索文檔時)都顯示錯誤消息“未經授權”。

在文檔中,它提到了ICredentials ,但是我無法從ServiceAccountCredential找到有關如何創建此ICredentials對象的任何信息。

我還在文檔中看到了一種允許公眾訪問以檢索文檔的方法,但是我嘗試了此方法,但該方法也不起作用。 奇怪的是我們可以下載縮略圖,但不能下載實際文檔。

誰能幫助我知道如何授權這些鏈接?

使用服務帳戶創建驅動器服務憑據與Oauth2幾乎相同。

var service = AuthenticationHelper.AuthenticateServiceAccount("1046123799103-6v9cj8jbub068jgmss54m9gkuk4q2qu8@developer.gserviceaccount.com",@"C:\Users\HPUser\Downloads\e8bf61cc9963.p12");

 /// <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="keyFilePath">Location of the Service account key file downloaded from Google Developer console https://console.developers.google.com</param>
        /// <returns></returns>
        public static DriveService AuthenticateServiceAccount(string serviceAccountEmail, string keyFilePath)
        {

            // check the file exists
            if (!File.Exists(keyFilePath))
            {
                Console.WriteLine("An Error occurred - Key file does not exist");
                return null;
            }

            string[] scopes = new string[] { DriveService.Scope.Drive };     // View analytics data            

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

                // Create the service.
                DriveService service = new DriveService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Drive API Sample",
                });
                return service;
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.InnerException);
                return null;

            }

上面的方法將返回一個驅動器服務,您可以用來進行任何其他調用。 這是我用來下載文件的方法。 一旦您從files.list獲得文件資源

var m = service.Files.List().Execute();

如您所見,它使用downloadURL下載文件。

/// <summary>
        /// Download a file
        /// Documentation: https://developers.google.com/drive/v2/reference/files/get
        /// </summary>
        /// <param name="_service">a Valid authenticated DriveService</param>
        /// <param name="_fileResource">File resource of the file to download</param>
        /// <param name="_saveTo">location of where to save the file including the file name to save it as.</param>
        /// <returns></returns>
        public static Boolean downloadFile(DriveService _service, File _fileResource, string _saveTo)
        {

            if (!String.IsNullOrEmpty(_fileResource.DownloadUrl))
            {
                try
                {
                    var x = _service.HttpClient.GetByteArrayAsync(_fileResource.DownloadUrl );
                    byte[] arrBytes = x.Result;
                    System.IO.File.WriteAllBytes(_saveTo, arrBytes);
                    return true;                  
                }
                catch (Exception e)
                {
                    Console.WriteLine("An error occurred: " + e.Message);
                    return false;
                }
            }
            else
            {
                // The file doesn't have any content stored on Drive.
                return false;
            }
        }

從教程Google Drive api C#下載中剝離的代碼

暫無
暫無

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

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