azure - 使用 Azure Functions 中的 Google API

标签 azure google-api google-drive-api google-oauth

我正在尝试使用 Azure 函数访问 Google Apis。目标是将多个 Google Sheets 的内容连接到 Azure SQL 数据库中。我一直在查看示例代码here但我不知道如何使用 Azure Functions 使其工作。

当我创建 AppFlowMetadata.csx 文件并使用“#load "AppFlowMetadata.csx"”在 run.csx 中引用它时,出现多个编译错误:

error CS0234: The type or namespace name 'Mvc' does not exist in the namespace 'System.Web' (are you missing an assembly reference?)

error CS0234: The type or namespace name 'Mvc' does not exist in the namespace 'Google.Apis.Auth.OAuth2' (are you missing an assembly reference?)

error CS0246: The type or namespace name 'FlowMetadata' could not be found (are you missing a using directive or an assembly reference?)

error CS0246: The type or namespace name 'Controller' could not be found (are you missing a using directive or an assembly reference?)

error CS0115: 'AppFlowMetadata.GetUserId(Controller)': no suitable method found to override

error CS0115: 'AppFlowMetadata.Flow': no suitable method found to override

AppFlwMetadata.csx:

using System;
using System.Web.Mvc;

using Google.Apis.Auth.OAuth2;
using Google.Apis.Auth.OAuth2.Flows;
using Google.Apis.Auth.OAuth2.Mvc;
using Google.Apis.Drive.v3;
using Google.Apis.Util.Store;

public class AppFlowMetadata : FlowMetadata
{
private static readonly IAuthorizationCodeFlow flow =
    new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
        {
            ClientSecrets = new ClientSecrets
            {
                ClientId = "PUT_CLIENT_ID_HERE",
                ClientSecret = "PUT_CLIENT_SECRET_HERE"
            },
            Scopes = new[] { DriveService.Scope.Drive },
            DataStore = new FileDataStore("Drive.Api.Auth.Store")
        });

public override string GetUserId(Controller controller)
{
    // In this sample we use the session to store the user identifiers.
    // That's not the best practice, because you should have a logic to identify
    // a user. You might want to use "OpenID Connect".
    // You can read more about the protocol in the following link:
    // https://developers.google.com/accounts/docs/OAuth2Login.
    var user = controller.Session["user"];
    if (user == null)
    {
        user = Guid.NewGuid();
        controller.Session["user"] = user;
    }
    return user.ToString();

}

public override IAuthorizationCodeFlow Flow
{
    get { return flow; }
}
}

项目.json:

{
"frameworks": {
"net46":{
  "dependencies": {
    "Google.Apis.Drive.v3": "1.25.0.834",
    "Google.Apis.Sheets.v4": "1.25.0.841",
    "Google.Apis.Auth":"1.25.0"
  }
}
}
}

有人成功使用 Azure 函数通过 Google Apis 进行身份验证吗?有关如何将 Google 示例应用到 Azure 的任何指导吗?

最佳答案

我还没有完全尝试过这个。 IMO 您将无法使用 Oauth2,我建议尝试使用服务帐户。

您必须弄清楚如何上传服务帐户 key 文件。

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

从 Google Drive 的我的 GitHub 示例项目中摘取的代码。 Serviceaccount.cs我还有一个关于 Drive API with service accounts 的教程

如果你无法让它工作,请告诉我,我可能必须自己尝试一下,这听起来是一个有趣的想法。

关于azure - 使用 Azure Functions 中的 Google API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43839197/

相关文章:

azure - 如何在Microsoft Azure上打开outline/shadowsocks服务器

azure - 处理来自不同 AD 租户中多个 Azure 订阅中存储帐户的 Blob 事件?

javascript - Google Drive OAuth 在某些浏览器上触发 origin_mismatch

android - 以编程方式访问文件共享链接 - Google Drive、Android

google-cloud-platform - 文件上传到Google Cloud Storage的速度很慢

azure - WorkerRole.cs 的目的是什么

azure - ServiceBus 重试策略不适用于 QueueClient

python - 获取自定义搜索的 cx ID,Google API - Python

google-api - Google 的 OAuth 身份验证是免费的吗?

python - 如何执行身份验证以验证 Google 应用内订阅