当前位置:  开发笔记 > 编程语言 > 正文

如何以编程方式提供凭据以在c#或vb.net中使用google drive api?

如何解决《如何以编程方式提供凭据以在c#或vb.net中使用googledriveapi?》经验,为你挑选了1个好方法。

我制作了一个程序,使用谷歌驱动器API从谷歌驱动器上的文件中读取数据.

第一次运行应用程序时,它会打开一个Web浏览器,要求使用google驱动器帐户登录.

我想为应用程序提供用户名和密码,以便自动获取凭据,以便用户无需知道我的google云端硬盘帐户的用户名和密码.

这是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#中的代码:

        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 files = listRequest.Execute()
            .Files;

DaImTo.. 5

不幸的是你无法嵌入这样的登录名和密码.我还有其他选择.

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

将服务帐户视为虚拟用户.您可以通过使用服务帐户电子邮件地址共享Google云端硬盘中的文件夹,授予其访问您的Google云端硬盘帐户的权限.

以下是使用服务帐户进行身份验证的示例代码.

/// 
    /// Authenticating to Google using a Service account
    /// Documentation: https://developers.google.com/accounts/docs/OAuth2#serviceaccount
    /// 
    /// From Google Developer console https://console.developers.google.com
    /// Location of the .p12 or Json Service account key file downloaded from Google Developer console https://console.developers.google.com
    /// AnalyticsService used to make requests against the Analytics API
    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:\Users\linda_l\Documents\Diamto Test Everything Project\ServiceAccountTest\Diamto Test Everything Project-145ed16d5d47.json");

从我的非官方谷歌驱动器示例项目serviceaccount.cs中删除了代码 我还有一篇文章更深入到服务帐户Google Developer Console服务帐户



1> DaImTo..:

不幸的是你无法嵌入这样的登录名和密码.我还有其他选择.

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

将服务帐户视为虚拟用户.您可以通过使用服务帐户电子邮件地址共享Google云端硬盘中的文件夹,授予其访问您的Google云端硬盘帐户的权限.

以下是使用服务帐户进行身份验证的示例代码.

/// 
    /// Authenticating to Google using a Service account
    /// Documentation: https://developers.google.com/accounts/docs/OAuth2#serviceaccount
    /// 
    /// From Google Developer console https://console.developers.google.com
    /// Location of the .p12 or Json Service account key file downloaded from Google Developer console https://console.developers.google.com
    /// AnalyticsService used to make requests against the Analytics API
    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:\Users\linda_l\Documents\Diamto Test Everything Project\ServiceAccountTest\Diamto Test Everything Project-145ed16d5d47.json");

从我的非官方谷歌驱动器示例项目serviceaccount.cs中删除了代码 我还有一篇文章更深入到服务帐户Google Developer Console服务帐户

推荐阅读
LEEstarmmmmm
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有