本文介绍了如何以编程方式提供凭据以在 c# 或 vb.net 中使用 google drive api?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个程序,该程序使用 google drive api 从 google drive 上的文件中读取数据.

I made a program that uses google drive api to read data from a file on google drive.

您第一次运行该应用程序时,它会打开一个网络浏览器,要求您使用 Google Drive 帐户登录.

the first time you run the app it opens a web browser asking to sign in with google drive account.

我想为应用提供用户名和密码,以便它自动获取凭据,这样用户就不需要知道我的 Google Drive 帐户的用户名和密码.

I want to provide the app the username and password so that it get the credentials automatically, so that users won't need to know the username and password of my google drive account.

这是vb.net中的代码:

here is the code in vb.net:

    Dim credential As UserCredential

    Using stream = New FileStream("client_secret.json", FileMode.Open, FileAccess.Read)
        Dim credPath As String = System.Environment.GetFolderPath(
            System.Environment.SpecialFolder.Personal)
        credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.json")

        credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
        GoogleClientSecrets.Load(stream).Secrets,
        Scopes,
        "user",
        CancellationToken.None,
        New FileDataStore(credPath, True)).Result
        'Console.WriteLine("Credential file saved to: " + credPath)
    End Using

    //I want to provide the username and password in the app so that it doesn't open a web browser asking for them

    ' Create Drive API service.
    Dim initializer = New BaseClientService.Initializer
    initializer.HttpClientInitializer = credential
    initializer.ApplicationName = ApplicationName
    Dim service = New DriveService(initializer)

    ' Define parameters of request.
    Dim listRequest As FilesResource.ListRequest = service.Files.List()
    listRequest.PageSize = 10
    listRequest.Fields = "nextPageToken, files(id, name)"

    ' List files.
    Dim files As IList(Of Google.Apis.Drive.v3.Data.File) = listRequest.Execute().Files

这里是 C# 中的代码:

here is the code in c#:

        UserCredential credential;

        using (var stream =
            new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
        {
            string credPath = System.Environment.GetFolderPath(
                System.Environment.SpecialFolder.Personal);
            credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.json");

            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                Scopes,
                "user",
                CancellationToken.None,
                new FileDataStore(credPath, true)).Result;
            //Console.WriteLine("Credential file saved to: " + credPath);
        }

        //I want to provide the username and password in the app so that it doesn't open a web browser asking for them

        // Create Drive API service.
        var service = new DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = ApplicationName,
        });

        // Define parameters of request.
        FilesResource.ListRequest listRequest = service.Files.List();
        listRequest.PageSize = 10;
        listRequest.Fields = "nextPageToken, files(id, name)";

        // List files.
        IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute()
            .Files;

推荐答案

很遗憾,您无法像这样嵌入登录名和密码.我确实有另一个选择.

Unfortunately you cant embed a login and password like that. I do have another option for you.

听起来您正试图允许用户访问您的个人 Google 云端硬盘帐户.在这种情况下,您应该使用服务帐户而不是 Oauth2.Oauth2 需要用户以网页的形式进行交互,以授予应用程序访问用户自己的谷歌驱动器帐户的权限.而服务帐号是由开发者在后台预先授权的.

It sounds like you are trying to allow users access to your personal Google drive account. In that case you should be using a service account and Not Oauth2. Oauth2 requires user interaction in the form of a webpage to grant an application access to the Users own google drive account. While service accounts are pre authorized by the developer in the background.

将服务帐户视为虚拟用户.您可以通过与服务帐户电子邮件地址共享您的 google 驱动器中的文件夹来授予它访问您的 google 驱动器帐户的权限.

Think of a service account as a dummy user. You can grant it access to your google drive account by sharing a folder in your google drive with the service accounts email address.

这里是一些使用服务帐户进行身份验证的示例代码.

Here is some sample code for authenticating with a service account.

/// <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="serviceAccountCredentialFilePath">Location of the .p12 or Json Service account key file downloaded from Google Developer console https://console.developers.google.com</param>
    /// <returns>AnalyticsService used to make requests against the Analytics API</returns>
    public static DriveService AuthenticateServiceAccount(string serviceAccountEmail, string serviceAccountCredentialFilePath)
    {
        try
        {
            if (string.IsNullOrEmpty(serviceAccountCredentialFilePath))
                throw new Exception("Path to the service account credentials file is required.");
            if (!File.Exists(serviceAccountCredentialFilePath))
                throw new Exception("The service account credentials file does not exist at: " + serviceAccountCredentialFilePath);
            if (string.IsNullOrEmpty(serviceAccountEmail))
                throw new Exception("ServiceAccountEmail is required.");

            // These are the scopes of permissions you need. It is best to request only what you need and not all of them
            string[] scopes = new string[] { AnalyticsReportingService.Scope.Analytics };             // View your Google Analytics data

            // For Json file
            if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".json")
            {
                GoogleCredential credential;
                using (var stream = new FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read))
                {
                    credential = GoogleCredential.FromStream(stream)
                         .CreateScoped(scopes);
                }

                // Create the  Analytics service.
                return new DriveService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Drive Service account Authentication Sample",
                });
            }
            else if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".p12")
            {   // If its a P12 file

                var certificate = new X509Certificate2(serviceAccountCredentialFilePath, "notasecret", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
                var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
                {
                    Scopes = scopes
                }.FromCertificate(certificate));

                // Create the  Drive service.
                return new DriveService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Drive Authentication Sample",
                });
            }
            else
            {
                throw new Exception("Unsupported Service accounts credentials.");
            }

        }
        catch (Exception ex)
        {
            Console.WriteLine("Create service account DriveService failed" + ex.Message);
            throw new Exception("CreateServiceAccountDriveFailed", ex);
        }
    }
}

用法:

  var service = AuthenticateServiceAccount("1046123799103-6v9cj8jbub068jgmss54m9gkuk4q2qu8@developer.gserviceaccount.com", @"C:Userslinda_lDocumentsDiamto Test Everything ProjectServiceAccountTestDiamto Test Everything Project-145ed16d5d47.json");

从我的非官方 Google Drive 示例项目中提取的代码 serviceaccount.cs 我还有一篇文章更深入地介绍了服务帐户Google 开发者控制台服务帐户

Code ripped from my unofficial google drive sample project serviceaccount.cs I also have an article that goes deeper into service accounts Google Developer console service account

这篇关于如何以编程方式提供凭据以在 c# 或 vb.net 中使用 google drive api?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-18 18:42