简体   繁体   English

已安装的应用程序的Google Drive Api c#

[英]Google Drive Api for installed application c#

Can someone please show a working example code of how to use google drive api for installed application? 有人可以展示如何使用谷歌驱动器api安装应用程序的工作示例代码? ( access_type=offline) I found a few explanations, but can't get to a working flow. (access_type = offline)我找到了一些解释,但无法进入工作流程。

Thanks 谢谢

Ok, What I used at least was not 'installed application', but 'web application'. 好吧,我至少使用的不是“安装的应用程序”,而是“网络应用程序”。 These are the steps to do: 这些是要做的步骤:

  1. Go to Google Developers Console and create a project. 转到Google Developers Console并创建一个项目。

  2. Go to APIs & Auth 转到API和Auth

  3. On APIs enable Drive API & Drive SDK. 在API上启用Drive API和Drive SDK。

4.On Credentials Create new Client ID for Web Application (Create your Consent screen, evev though we won't use it.) 4.在凭据上为Web应用程序创建新的客户端ID(创建您的同意屏幕,尽管我们不会使用它。)

In the Create Client ID window, add the url " https://developers.google.com/oauthplayground " to the AUTHORIZED REDIRECT URIS. 在“创建客户端ID”窗口中,将网址“ https://developers.google.com/oauthplayground ”添加到AUTHORIZED REDIRECT URIS。

5.Go to the url you added on number 4 5.转到您在第4号添加的网址

6.Click the gear on the right and configure: 6.单击右侧的齿轮并配置:

OAuth flow: Server-side

Access type: Offline

Use your own OAuth credentials: Tick

Then copy your Client ID & Secret from the console.

7.On the left, choose Drive API -> https://www.googleapis.com/auth/drive , click Authorize APIs 7.在左侧,选择Drive API - > https://www.googleapis.com/auth/drive ,单击授权API

8.A new window will open, asking you to accept Google OAuth... click Accept. 8.将打开一个新窗口,要求您接受Google OAuth ...单击“接受”。

9.Click Exchange authorizaion code for tokens. 9.单击令牌的Exchange授权代码。

10.Copy & Save the Acess & Refresh tokens. 10.Copy&Save the Acess&Refresh令牌。

The code: 编码:

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

This is my helper class I use Kinda tweeked it for you for Google Drive. 这是我的助手课程,我使用Kinda为你推荐Google Drive。 Remember a Service account is NOT YOU. 请记住服务帐户不是您。 Just because you create it does not mean that it will have access to the files on your Google drive account. 仅仅因为您创建它并不意味着它可以访问您的Google云端硬盘帐户中的文件。 Service accounts are there own entity there own sudu user. 服务帐户有自己的实体,有自己的sudu用户。 This creates the basic drive service that you can use to follow the other tutorials I have created that use normal Oauth2 这将创建基本的驱动器服务,您可以使用它来遵循我使用普通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;

    }
}

you call it like this 你这么称呼它

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

Tutorial : Google Drive API with Service Account C# 教程: 带有服务帐户C#的Google Drive API

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM