【问题标题】:Google drive - alter a shared spreadsheet without oauthGoogle 云端硬盘 - 无需 oauth 即可更改共享电子表格
【发布时间】:2018-08-23 02:29:08
【问题描述】:

我想以编程方式编辑 Google 云端硬盘上的共享电子表格。 我正在使用 C#

当用户单击按钮时,我的代码应使用公司开发帐户 + 密码来访问 google drive 上的电子表格并更新日期字段。这就是它需要做的所有事情。

在我看来,oAuth 要求用户自己通过 google 进行身份验证,或者至少这是我从 Google.Apis.Auth.OAuth2AuthorizeAsync() 得到的印象

    //
    // Summary:
    //     Asynchronously authorizes the specified user. Requires user interaction; see
    //     Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker remarks for more details.
    //

这不是我需要或想要的,但围绕它的文档似乎完全不透明......也许我在这里遗漏了一些东西? 有人知道另一种方法吗?

【问题讨论】:

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


【解决方案1】:

为了更新您需要进行身份验证的任何内容,即使工作表设置为公开并且任何人都可以访问它。从编程上讲,您仍然需要进行身份验证。

您应该考虑使用的是服务帐户。如果您使用服务帐户电子邮件地址与服务帐户共享工作表,则服务帐户就像虚拟用户。然后它将无需经过身份验证即可访问工作表。

public static class ServiceAccountExample
{

    /// <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 SheetsService AuthenticateServiceAccount(string serviceAccountEmail, string serviceAccountCredentialFilePath, string[] scopes)
    {
        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.");                

            // 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 SheetsService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Sheets 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  Sheets service.
                return new SheetsService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Sheets Authentication Sample",
                });
            }
            else
            {
                throw new Exception("Unsupported Service accounts credentials.");
            }

        }
        catch (Exception ex)
        {                
            throw new Exception("CreateServiceAccountSheetsFailed", ex);
        }
    }
}

从我的示例项目ServiceAccount.cs中提取的代码

【讨论】:

  • 美丽。正是我想要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-11
  • 1970-01-01
  • 2015-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-25
相关资源
最近更新 更多