Google Drive API IAuthenticator

我的未来我决定 提交于 2020-01-16 00:21:55

问题


I am trying to integrate my ASP.NET C# application with the Google Drive API. We have successfully stored documents as pdf onto our drive storage account, but now we are trying to retrieve and download the file.

We make the call and it gives us data back. My problem is that it gives me several download links and each of these links (when used to retrieve the document) gives an error saying "Unauthorized".

In the documentation it mentions ICredentials, but I cannot find anything about how to create this ICredentials object from our ServiceAccountCredential.

I also saw on the documentation a way to allow public access to retrieve the document, but I tried this and it did not work either. The strange thing is we can download the thumbnail image, but not the actual document.

Can anyone help me to know how to get these links authorized?


回答1:


Creating a drive service using a service account Credential is pretty much the same as with 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;

            }

The above method will return a drive service that you can use to make any other calls. This is the method I use to download a file. Once you get the fileresource back from files.list

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

As you can see it uses downloadURL to download the file.

/// <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;
            }
        }

Code ripped from tutorial Google Drive api C# download



来源:https://stackoverflow.com/questions/28571201/google-drive-api-iauthenticator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!