从 Azure Functions 使用 Google API
Posted
技术标签:
【中文标题】从 Azure Functions 使用 Google API【英文标题】:Using Google Apis from Azure Functions 【发布时间】:2017-05-08 03:10:02 【问题描述】:我正在尝试使用 Azure 功能访问 Google API。目标是连接以将多个 Google 表格的内容加载到 Azure SQL 数据库中。我一直在查看示例代码 here,但我不知道如何使用 Azure Functions 使其工作。
当我创建一个 AppFlowMetadata.csx 文件并在我的 run.csx 中使用 '#load "AppFlowMetadata.csx"' 引用它时,我收到多个编译错误:
错误 CS0234:命名空间“System.Web”中不存在类型或命名空间名称“Mvc”(您是否缺少程序集引用?)
错误 CS0234:命名空间“Google.Apis.Auth.OAuth2”中不存在类型或命名空间名称“Mvc”(您是否缺少程序集引用?)
错误 CS0246:找不到类型或命名空间名称“FlowMetadata”(您是否缺少 using 指令或程序集引用?)
错误 CS0246:找不到类型或命名空间名称“Controller”(您是否缺少 using 指令或程序集引用?)
错误 CS0115:“AppFlowMetadata.GetUserId(Controller)”:找不到合适的方法来覆盖
错误 CS0115:“AppFlowMetadata.Flow”:找不到合适的方法来覆盖
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;
project.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 API 进行身份验证?有关如何将 Google 示例应用到 Azure 的任何指导?
【问题讨论】:
我不确定如何使用 Oauth2 进行身份验证。 webhook 必须请求访问,然后接受来自永远无法工作的身份验证服务器的返回。你打算如何启动它? 按计划,我计划在我的 Google Drive 中提取文件元数据,查看自上次提取后是否更新了任何工作表,然后将内容加载到 Azure sql DB。 谁的驱动器帐户 我自己的帐户。 尝试使用服务帐户而不是 Oauth2 可能会起作用 【参考方案1】:我还没有完全尝试过这个。 IMO 您将无法使用 Oauth2,我建议您尝试使用服务帐户。
您必须弄清楚如何上传服务帐户密钥文件。
/// <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 驱动器的 My GitHub 示例项目中提取的代码。 Serviceaccount.cs我还有一个关于Drive API with service accounts的教程
如果你不能让它工作,让我知道我可能不得不尝试自己,这听起来是一个有趣的想法。
【讨论】:
您知道如何使用这个新的服务帐户共享我个人 Google 云端硬盘中的文件,以便它可以访问它吗?我输入什么电子邮件地址来代表服务帐户? 谢谢,我可以将此示例用于 Google 表格的另一个类似用例以上是关于从 Azure Functions 使用 Google API的主要内容,如果未能解决你的问题,请参考以下文章
如何从 Azure 移动应用服务调用 HTTP(Azure Functions)?
如何从 Azure Functions 中的存储容器读取多个文件
如何从 Key Vault 自动映射 Azure Functions 机密