【问题标题】:Google Drive Api for installed application c#用于已安装应用程序 c# 的 Google Drive Api
【发布时间】:2015-02-10 12:30:28
【问题描述】:

有人可以展示如何使用 google drive api 安装应用程序的工作示例代码吗? (access_type=离线) 我找到了一些解释,但无法找到工作流程。

谢谢

【问题讨论】:

  • 谢谢,但这不是我要找的。我不希望用户接受任何东西,实际上我根本不需要用户(一开始),我希望始终从我为应用程序打开的同一个帐户登录。
  • 那你需要查看一个服务账号。我没有任何带有服务帐户的纯驱动器示例。代码更简单daimto.com/googleanalytics-authentication-csharp/… 没有多少人通过服务帐户使用 Google 驱动器,因为您看不到通过网站上传的内容。
  • 听起来不错,我会检查它并让您知道它是否有效。谢谢
  • 它工作我已经做到了:) 我只是还没有任何教程。

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


【解决方案1】:

好的,我至少使用的不是“已安装的应用程序”,而是“网络应用程序”。 这些是要做的步骤:

  1. 转到 Google Developers Console 并创建一个项目。

  2. 转到 API 和身份验证

  3. 在 API 上启用 Drive API 和 Drive SDK。

4.On Credentials 为 Web 应用程序创建新的客户端 ID(创建您的同意屏幕,尽管我们不会使用它。)

在“创建客户端 ID”窗口中,将 URL“https://developers.google.com/oauthplayground”添加到 AUTHORIZED REDIRECT URIS。

5.转到您在数字 4 上添加的网址

6.点击右侧齿轮并配置:

OAuth flow: Server-side

Access type: Offline

Use your own OAuth credentials: Tick

Then copy your Client ID & Secret from the console.

7.在左侧选择Drive API -> https://www.googleapis.com/auth/drive,点击Authorize APIs

8. 将打开一个新窗口,要求您接受 Google OAuth...点击接受。

9.点击兑换代币授权码。

10.复制并保存访问和刷新令牌。

代码:

private static DriveService CreateServie(string applicationName)
{
  var tokenResponse = new TokenResponse
  {
    AccessToken = yourAccessToken,
    RefreshToken = yourRefreshToken,
  };

  var apiCodeFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
  {
    ClientSecrets = new ClientSecrets
    {
      ClientId = yourClientID,
      ClientSecret = yourClientSecret
    },
    Scopes = new[] { DriveService.Scope.Drive },
    DataStore = new FileDataStore(applicationName)
  });

  var credential = new UserCredential(apiCodeFlow, yourEMail, tokenResponse);

  var service = new DriveService(new BaseClientService.Initializer
  {
    HttpClientInitializer = credential,
    ApplicationName = applicationName
  });

  return service;
}

【讨论】:

    【解决方案2】:

    这是我的助手类,我使用 Kinda 为您在 Google Drive 中使用了它。请记住,服务帐户不是您。仅仅因为您创建了它并不意味着它可以访问您的 Google 云端硬盘帐户中的文件。服务帐户有自己的实体,有自己的 sudu 用户。这将创建基本驱动服务,您可以使用它来遵循我创建的使用普通 Oauth2 的其他教程

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

    你这样称呼它

    var x = AuthenticationHelper.AuthenticateServiceAccount("46123799103-6v9cj8jbub068jgmss54m9gkuk4q2qu8@developer.gserviceaccount.com",@"C:\Users\LL\Downloads\Diamto Test Everything Project-e8bf61cc9963.p12");
    

    教程:Google Drive API with Service Account C#

    【讨论】:

    • 感谢您的样品。我正在尝试,但出现错误:错误:“invalid_grant”,描述:“”,Uri:“”
    • 仔细检查服务帐户电子邮件地址和密钥文件位置。您需要将密钥文件 c:\temp\x.p12 的完整路径发送给它
    • 这是我的代码: var certificate = new X509Certificate2("D:\\Temp\\QRApp-f21b8eb0bc66.p12", "notasecret", X509KeyStorageFlags.Exportable); ServiceAccountCredential credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer("qrappdrive@gmail.com") { Scopes = scopes }.FromCertificate(certificate));怎么了?
    • qrappdrive@gmail.com
    • 好的。固定为: var certificate = new X509Certificate2("D:\\Temp\\QRApp-f21b8eb0bc66.p12", "notasecret", X509KeyStorageFlags.Exportable); ServiceAccountCredential credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer("867154538822-5ilhfkiisn4l4ggnfvukk2dvij0vib0g@developer.gserviceaccount.com") { Scopes = scopes }.FromCertificate(certificate));但它仍然给出同样的错误。
    猜你喜欢
    • 2014-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-05
    • 1970-01-01
    • 2016-05-11
    • 1970-01-01
    • 2011-02-03
    相关资源
    最近更新 更多