Google Drive API IAuthenticator [英] Google Drive API IAuthenticator

查看:284
本文介绍了Google Drive API IAuthenticator的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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



在文档中提到 ICredentials ,但我找不到任何有关如何创建我们的 ServiceAccountCredential 中的ICredentials 对象。

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

任何人都可以帮助我知道如何获得这些链接的授权吗? 使用服务帐户创建驱动器服务Credential与使用Oauth2的方式几乎相同。

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

///< summary>
///使用服务帐户向Google进行身份验证
///文档:https://developers.google.com/accounts/docs/OAuth2#serviceaccount
///< /总结>
///< param name =serviceAccountEmail>从Google Developer Console https://console.developers.google.com< / param>
///< param name =keyFilePath>从Google Developer控制台下载的服务帐户密钥文件的位置https://console.developers.google.com< / param>
///<返回>< /返回>
public static DriveService AuthenticateServiceAccount(string serviceAccountEmail,string keyFilePath)
{

//检查文件是否存在
if(!File.Exists(keyFilePath))
{
Console.WriteLine(发生错误 - 密钥文件不存在);
返回null;
}

string [] scopes = new string [] {DriveService.ScopeDrive}; //查看分析数据

var certificate = new X509Certificate2(keyFilePath,notasecret,X509KeyStorageFlags.Exportable);
尝试
{
ServiceAccountCredential凭证=新ServiceAccountCredential(
新ServiceAccountCredential.Initializer(serviceAccountEmail)
{
范围=范围
} .FromCertificate (证书));

//创建服务。
DriveService service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer =凭证,
ApplicationName =Drive API Sample,
});
退货服务;
}
catch(Exception ex)
{

Console.WriteLine(ex.InnerException);
返回null;






$ b

上述方法将返回一个可以使用的驱动器服务拨打任何其他电话。这是我用来下载文件的方法。一旦你从files.list中获得了fileresource,你就可以使用这个文件来创建一个文件。

  var m = service.Files.List()。 

您可以看到它使用downloadURL下载文件。

  ///< summary> 
///下载文件
///文档:https://developers.google.com/drive/v2/reference/files/get
///< / summary>
///< param name =_ service> a有效的认证DriveService< / param>
///< param name =_ fileResource>要下载的文件的文件资源< / param>
///< param name =_ saveTo>保存文件的位置(包括文件名称以将其保存为。< / param>
///<返回>< /返回>
如果(!String.IsNullOrEmpty(_fileResource.DownloadUrl))
{$ b public static Boolean $ b尝试
{
var x = _service.HttpClient.GetByteArrayAsync(_fileResource.DownloadUrl);
byte [] arrBytes = x.Result;
System.IO.File.WriteAllBytes(_saveTo,arrBytes);
返回true;

catch(Exception e)
{
Console.WriteLine(发生错误:+ e.Message);
返回false;
}
}
else
{
//该文件没有存储在Drive上的任何内容。
返回false;


源自教程的代码 Google Drive api C#下载


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?

解决方案

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

这篇关于Google Drive API IAuthenticator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆