使用Azure函数中的Google API
我正在尝试使用Azure函数访问Google API。目标是连接以将多个Google工作表的内容加载到Azure SQL数据库中。我一直在看示例代码,但我不知道如何使用Azure函数使其工作 当我创建一个AppFlowMetadata.csx文件并在run.csx中使用“#load”AppFlowMetadata.csx”引用它时,会出现多个编译错误: 错误CS0234:命名空间“System.Web”中不存在类型或命名空间名称“Mvc”(是否缺少程序集引用?) 错误CS0234:命名空间“Google.api.Auth.OAuth2”中不存在类型或命名空间名称“Mvc”(是否缺少程序集引用?) 错误CS0246:找不到类型或命名空间名称“FlowMetadata”(是否缺少using指令或程序集引用?) 错误CS0246:找不到类型或命名空间名称“Controller”(是否缺少using指令或程序集引用?) 错误CS0115:'AppFlowMetadata.GetUserId(控制器)':未找到可重写的合适方法 错误CS0115:“AppFlowMetadata.Flow”:找不到可重写的合适方法 AppFlwMetadata.csx:使用Azure函数中的Google API,azure,google-api,google-drive-api,google-oauth,Azure,Google Api,Google Drive Api,Google Oauth,我正在尝试使用Azure函数访问Google API。目标是连接以将多个Google工作表的内容加载到Azure SQL数据库中。我一直在看示例代码,但我不知道如何使用Azure函数使其工作 当我创建一个AppFlowMetadata.csx文件并在run.csx中使用“#load”AppFlowMetadata.csx”引用它时,会出现多个编译错误: 错误CS0234:命名空间“System.Web”中不存在类型或命名空间名称“Mvc”(是否缺少程序集引用?) 错误CS0234:命名空间“Go
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,我建议您尝试使用服务帐户 您必须弄清楚如何上传服务帐户密钥文件
/// <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进行身份验证
///文件:https://developers.google.com/accounts/docs/OAuth2#serviceaccount
///
///从谷歌开发者控制台https://console.developers.google.com
///从Google开发者控制台下载的.p12或Json服务帐户密钥文件的位置https://console.developers.google.com
///AnalyticsService用于针对Analytics API发出请求
公共静态驱动器服务验证ServiceAccount(字符串serviceAccountEmail、字符串serviceAccountCredentialFilePath)
{
尝试
{
if(string.IsNullOrEmpty(serviceAccountCredentialFilePath))
抛出新异常(“需要服务帐户凭据文件的路径”);
如果(!File.Exists(serviceAccountCredentialFilePath))
抛出新异常(“服务帐户凭据文件不存在于:“+serviceAccountCredentialFilePath”);
if(string.IsNullOrEmpty(serviceAccountEmail))
抛出新异常(“需要ServiceAccountEmail”);
//这些是您需要的权限范围。最好只请求您需要的权限,而不是所有权限
string[]scopes=新字符串[]{AnalyticsReportingService.Scope.Analytics};//查看您的Google分析数据
//对于Json文件
if(Path.GetExtension(serviceAccountCredentialFilePath.ToLower()==“.json”)
{
谷歌认证证书;
使用(var stream=newfilestream(serviceAccountCredentialFilePath,FileMode.Open,FileAccess.Read))
{
credential=GoogleCredential.FromStream(流)
.CreateScoped(范围);
}
//创建分析服务。
返回新的DriveService(新的BaseClientService.Initializer()
{
HttpClientInitializer=凭证,
ApplicationName=“驱动器服务帐户验证示例”,
});
}
else if(Path.GetExtension(serviceAccountCredentialFilePath.ToLower()==“.p12”)
{//如果是P12文件
var证书=新的X509Certificate2(serviceAccountCredentialFilePath,“notasecret”,X509KeyStrageFlags.MachineKeySet | X509KeyStrageFlags.Exportable);
var凭证=新ServiceAccountCredential(新ServiceAccountCredential.Initializer(serviceAccountEmail)
{
范围=范围
}.FromCertificate(证书));
//创建驱动器服务。
返回新的DriveService(新的BaseClientService.Initializer()
{
HttpClientInitializer=凭证,
ApplicationName=“驱动器身份验证示例”,
});
}
其他的
{
抛出新异常(“不支持的服务帐户凭据”);
}
}
捕获(例外情况除外)
{
Console.WriteLine(“创建服务帐户驱动服务失败”+ex.Message);
抛出新异常(“CreateServiceAccountDriveFailed”,ex);
}
}
}
从我的google drive GitHub示例项目中提取的代码。我也有一个关于
如果你不能让它工作,让我知道我可能不得不尝试自己,这听起来像一个有趣的想法 我不确定如何使用Oauth2进行身份验证。webhook必须请求访问,然后接受来自auth服务器的返回,而该服务器永远不会工作。你打算怎么启动它?按照计划,我计划在我的谷歌硬盘中提取文件元数据,看看自上次提取以来是否有任何表被更新,然后将内容加载到Azure sql DB中。谁的驱动器帐户我自己的帐户。尝试使用服务帐户而不是Oauth2它可能会起作用。你知道我如何在我的个人google驱动器中与这个新的服务帐户共享一个文件,以便它可以访问它吗?我应该输入什么电子邮件地址来表示服务帐户?谢谢,我可以用这个例子来描述另一个与Google Sheets类似的用例