【问题标题】:Get the google docs api refresh token and access token using Asp.Net MVc使用 Asp.Net MVc 获取 google docs api 刷新令牌和访问令牌
【发布时间】:2016-10-07 06:01:57
【问题描述】:

任何人都可以帮助我第一次在 asp .Net MVC 中获取 google docs api 刷新令牌。我有客户端 ID 和客户端 Secrete,从这里我应该如何获取刷新令牌以及从刷新令牌进一步我应该如何获取访问令牌来访问驱动器的谷歌 api。

【问题讨论】:

  • 您查看过哪个版本的 google docs api?
  • 我用的是google api v3。
  • 我仍然假设您的意思是 Google Drive API,因为 Google docs API 实际上并不是一个东西

标签: asp.net-mvc google-api google-docs-api google-api-dotnet-client


【解决方案1】:

他们还没有对Drive API V3 的示例代码做很多工作。我不会使用所有这些范围来选择您需要的范围,此代码是预先生成的。

NuGet 包

下午>Install-Package Google.Apis.Drive.v3

    /// <summary>
    /// This method requests Authentication from a user using Oauth2.  
    /// Credentials are stored in System.Environment.SpecialFolder.Personal
    /// Documentation https://developers.google.com/accounts/docs/OAuth2
    /// </summary>
    /// <param name="clientSecretJson">Path to the client secret json file from Google Developers console.</param>
    /// <param name="userName">Identifying string for the user who is being authentcated.</param>
    /// <returns>DriveService used to make requests against the Drive API</returns>
    public static DriveService AuthenticateOauth(string clientSecretJson, string userName)
    {
        try
        {
            if (string.IsNullOrEmpty(userName))
                throw new Exception("userName is required.");
            if (!File.Exists(clientSecretJson))
                throw new Exception("clientSecretJson file does not exist.");

            // 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[] { DriveService.Scope.Drive,                   // View and manage the files in your Google Drive
                                             DriveService.Scope.DriveAppdata,            // View and manage its own configuration data in your Google Drive
                                             DriveService.Scope.DriveFile,               // View and manage Google Drive files and folders that you have opened or created with this app
                                             DriveService.Scope.DriveMetadata,           // View and manage metadata of files in your Google Drive
                                             DriveService.Scope.DriveMetadataReadonly,   // View metadata for files in your Google Drive
                                             DriveService.Scope.DrivePhotosReadonly,     // View the photos, videos and albums in your Google Photos
                                             DriveService.Scope.DriveReadonly,           // View the files in your Google Drive
                                             DriveService.Scope.DriveScripts};           // Modify your Google Apps Script scripts' behavior
            UserCredential credential;
            using (var stream = new FileStream(clientSecretJson, FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials/apiName");

                // Requesting Authentication or loading previously stored authentication for userName
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
                                                                         scopes,
                                                                         userName,
                                                                         CancellationToken.None,
                                                                         new FileDataStore(credPath, true)).Result;
            }

            // Create Drive API service.
            return new DriveService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Drive Authentication Sample",
                });
        }
        catch (Exception ex)
        {
            Console.WriteLine("Create Oauth2 DriveService failed" + ex.Message);
            throw new Exception("CreateOauth2DriveFailed", ex);
        }
    }

服务帐号 Json 密钥文件不是 p12

 /// <summary>
    /// Authenticating to Google using a Service account
    /// Documentation: https://developers.google.com/accounts/docs/OAuth2#serviceaccount
    /// 
    /// Note: Not all APIs support service accounts I cant garentee this will work.   If you find an api that doesnt support service accoutns contact me 
    ///       me at www.daimto.com and I will remove it from auto genration of this APIs sample project.
    /// </summary>
    /// <param name="serviceAccountEmail">From Google Developer console https://console.developers.google.com</param>
    /// <param name="serviceAccountCredentialFilePath">Location of the Json Service account key file downloaded from Google Developer console https://console.developers.google.com</param>
    /// <returns>DriveService used to make requests against the Drive API</returns>
    public static DriveService AuthenticateServiceAccount(string serviceAccountCredentialFilePath)
    {
        try
        {
            if (string.IsNullOrEmpty(serviceAccountCredentialFilePath))
                throw new Exception("Path to the .JSon service account credentials file is required.");
            if (!File.Exists(serviceAccountCredentialFilePath))
                throw new Exception("The service account credentials .JSon file does not exist at:" + serviceAccountCredentialFilePath);

            // 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[] { DriveService.Scope.Drive,                   // View and manage the files in your Google Drive
                                             DriveService.Scope.DriveAppdata,            // View and manage its own configuration data in your Google Drive
                                             DriveService.Scope.DriveFile,               // View and manage Google Drive files and folders that you have opened or created with this app
                                             DriveService.Scope.DriveMetadata,           // View and manage metadata of files in your Google Drive
                                             DriveService.Scope.DriveMetadataReadonly,   // View metadata for files in your Google Drive
                                             DriveService.Scope.DrivePhotosReadonly,     // View the photos, videos and albums in your Google Photos
                                             DriveService.Scope.DriveReadonly,           // View the files in your Google Drive
                                             DriveService.Scope.DriveScripts};           // Modify your Google Apps Script scripts' behavior
            Stream stream = new FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
            var credential = GoogleCredential.FromStream(stream).CreateScoped(scopes);

            // Create the  Drive service.
            return new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "Drive Authentication Sample",
            });
        }
        catch (Exception ex)
        {
            Console.WriteLine("Create service account DriveService failed" + ex.Message);
            throw new Exception("CreateServiceAccountDriveServiceFailed", ex);
        }
    }

如果您需要其他任何东西,请告诉我我已经构建了部分示例项目。

【讨论】:

  • 非常感谢 DalmTo 。我成功获得了 UserCredential 和 DriveService。您能否让我知道我的网站访问者可以将文件上传到我的谷歌驱动器,我将在后台授权 oauth,即目前它要求登录。那么我该如何实现呢?
  • 如果您想让人们上传到您的帐户。您应该考虑使用服务帐户而不是 Oauth2。然后,您可以与服务帐户共享您的驱动器帐户上的文件夹。服务帐户是一种虚拟用户,然后服务帐户可以上传到驱动器文件夹只需记住服务帐户需要更新文件的权限以在上传后授予您权限,否则您的驱动器帐户上有文件您没有访问权限。
  • 在您询问之前有更多用于服务帐户身份验证的代码。和我的服务帐户教程,让您了解daimto.com/google-developer-console-service-account 的概念
  • 非常感谢 DalmTo 我能够使用服务帐户在服务器端上传、打开、删除和下载文件内容。注意您的教程。
  • 非常感谢 DalmTo 我能够使用服务帐户在服务器端上传、打开、删除和下载文件内容。注意您的教程。我正在使用链接“drive.google.com/file/d/item.Id/view?usp=drivesdk”打开文件。现在我想做的是编辑文档或想在编辑模式下打开文档你能告诉我我该怎么做吗?它将保存到原始文件中。而不是创建新文件。
猜你喜欢
  • 2013-06-14
  • 2014-07-15
  • 2019-06-29
  • 2015-11-26
  • 2015-07-19
  • 2015-01-08
  • 2020-12-11
  • 2017-09-26
  • 1970-01-01
相关资源
最近更新 更多