【问题标题】:Azure Function - Call Google API from within Azure Function (C#)Azure Function - 从 Azure Function (C#) 中调用 Google API
【发布时间】:2020-08-10 15:41:05
【问题描述】:

我正在尝试使用 .NET Core 创建一个 Azure 函数来调用 YouTube API 以检索我的视频的一些指标。

在调用 API 之前,我需要在服务器到服务器的方法中通过 Google 进行身份验证,因为此功能将每天运行,无需用户交互。

我已经关注了许多示例 (https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth),但在从 Azure 运行时我没有获得正确的身份验证。

这可能吗?任何人都可以指出这个工作的一个例子吗?

【问题讨论】:

标签: azure azure-functions


【解决方案1】:

对于服务器到服务器的交互,您需要一个service account,这是一个属于您的应用程序而不是单个最终用户的帐户。 您的应用程序代表服务帐户调用 Google API,无需用户同意

public class Program
{
    // A known public activity.
    private static String ACTIVITY_ID = "z12gtjhq3qn2xxl2o224exwiqruvtda0i";

    public static void Main(string[] args)
    {
        Console.WriteLine("Plus API - Service Account");
        Console.WriteLine("==========================");

        String serviceAccountEmail = "SERVICE_ACCOUNT_EMAIL_HERE";

        var certificate = new X509Certificate2(@"key.p12", "notasecret", X509KeyStorageFlags.Exportable);

        ServiceAccountCredential credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
            {
                Scopes = new[] { PlusService.Scope.PlusMe }
            }.FromCertificate(certificate));

        // Create the service.
        var service = new PlusService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "Plus API Sample",
        });

        Activity activity = service.Activities.Get(ACTIVITY_ID).Execute();
        Console.WriteLine("  Activity: " + activity.Object.Content);
        Console.WriteLine("  Video: " + activity.Object.Attachments[0].Url);

        Console.WriteLine("Press any key to continue...");
        Console.ReadKey();
    }
}

上面的示例代码创建了一个ServiceAccountCredential。设置了所需的范围,并调用了FromCertificate,它从给定的X509Certificate2 加载私钥。与所有其他示例代码一样,凭据设置为HttpClientInitializer

有关服务帐户流程的更多详细信息,您可以参考此article

【讨论】:

  • 您也可以使用桌面流程。它只需要一次性同意,可以在 oauth2 操场上完成。 Google 似乎不推荐服务到服务帐户。
猜你喜欢
  • 2018-08-13
  • 2019-04-08
  • 2021-10-20
  • 1970-01-01
  • 1970-01-01
  • 2019-04-29
  • 1970-01-01
  • 1970-01-01
  • 2020-02-15
相关资源
最近更新 更多