【问题标题】:Google Drive API IAuthenticatorGoogle Drive API IAuthenticator
【发布时间】:2015-02-18 15:29:44
【问题描述】:

我正在尝试将我的 ASP.NET C# 应用程序与 Google Drive API 集成。我们已成功地将文档作为 pdf 存储到我们的驱动器存储帐户中,但现在我们正在尝试检索和下载该文件。

我们拨打电话,它会将数据返回给我们。我的问题是它给了我几个下载链接,每个链接(当用于检索文档时)都会给出一个错误,说“未经授权”。

在文档中提到了ICredentials,但我找不到任何关于如何从我们的ServiceAccountCredential 创建这个ICredentials 对象的信息。

我还在文档中看到了一种允许公共访问以检索文档的方法,但我尝试了这个,它也不起作用。奇怪的是我们可以下载缩略图,但不能下载实际文档。

谁能帮助我知道如何获得这些链接的授权?

【问题讨论】:

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


    【解决方案1】:

    使用服务帐户凭据创建驱动器服务与使用 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# download 中提取的代码

    【讨论】:

    • 感谢您的帮助。让我进一步澄清一下我们的问题是什么:
    • 我们想将一个文档上传到我们的存储帐户并让它给我们一个下载链接,然后我们想将该链接放在我们的网站上以让用户下载该文件。我们希望的另一个选项可能是使用其中一个链接来允许我们网站的用户在 iframe 或其他东西中查看文件。当我们尝试时,所有这些链接都显示“未经授权”,所以这仍然不能完全按照我们需要的方式工作。你知道有什么方法可以让这个 api 调用以这种方式工作吗?再次感谢您的帮助。
    • 如果您希望生成的下载链接可供任何拥有该链接的人使用,您可能需要在上传文件时设置适当的权限。
    猜你喜欢
    • 2013-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多