【问题标题】:Authorize Google analytics data from a web application从 Web 应用程序授权 Google 分析数据
【发布时间】:2022-09-08 16:59:04
【问题描述】:

我正在尝试将 ASP.NET Core 6 MVC Web 应用程序授权给 Google 分析数据 API。

[GoogleScopedAuthorize("https://www.googleapis.com/auth/analytics.readonly")]
public async Task<IActionResult> Index([FromServices] IGoogleAuthProvider auth)
{
    var cred = await auth.GetCredentialAsync();
    
    var client = await BetaAnalyticsDataClient.CreateAsync(CancellationToken.None);

    var request = new RunReportRequest
    {
        Property = "properties/" + XXXXX,
        Dimensions = {new Dimension {Name = "date"},},
        Metrics = {new Metric {Name = "totalUsers"},new Metric {Name = "newUsers"}},
        DateRanges = {new DateRange {StartDate = "2021-04-01", EndDate = "today"},},
    };

    var response = await client.RunReportAsync(request);
}        

授权按预期进行;我得到了一个访问令牌。

我似乎无法弄清楚如何将凭据应用于BetaAnalyticsDataClient

当我运行它而不将其应用于BetaAnalyticsDataClient 时,我收到以下错误:

InvalidOperationException:应用程序默认凭据不可用。如果在 Google Compute Engine 中运行,它们就可用。否则,必须定义环境变量 GOOGLE_APPLICATION_CREDENTIALS 指向定义凭据的文件。请参阅https://developers.google.com/accounts/docs/application-default-credentials 了解更多信息。

我目前没有使用GOOGLE_APPLICATION_CREDENTIALS,因为它是在programs.cs 中配置的。我认为不需要在 program.cs 中配置客户端 ID 和机密,并添加一个 env var。

为什么它不只是获取控制器运行时已经提供的授权?

builder.Services
    .AddAuthentication(o =>
    {
        // This forces challenge results to be handled by Google OpenID Handler, so there's no
        // need to add an AccountController that emits challenges for Login.
        o.DefaultChallengeScheme = GoogleOpenIdConnectDefaults.AuthenticationScheme;
        // This forces forbid results to be handled by Google OpenID Handler, which checks if
        // extra scopes are required and does automatic incremental auth.
        o.DefaultForbidScheme = GoogleOpenIdConnectDefaults.AuthenticationScheme;
        // Default scheme that will handle everything else.
        // Once a user is authenticated, the OAuth2 token info is stored in cookies.
        o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    })
    .AddCookie()
    .AddGoogleOpenIdConnect(options =>
    {
        options.ClientId = builder.Configuration["Google:ClientId"];
        options.ClientSecret = builder.Configuration["Google:ClientSecret"];
    });

是否有另一种方法可以使用我无法找到的网络应用程序进行授权。我确实在源代码中做了一些修改,但我似乎找不到应用它的方法。

【问题讨论】:

    标签: c# asp.net-core-mvc google-oauth google-analytics-api google-api-dotnet-client


    【解决方案1】:

    经过大量挖掘后,我设法发现可以创建自己的客户端构建器并在那里应用凭据。

    var clientBuilder = new BetaAnalyticsDataClientBuilder()
        {
            Credential = await auth.GetCredentialAsync()
        };
        var client = await clientBuilder.BuildAsync();
    

    希望这对其他人有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-22
      • 2011-08-23
      • 2018-04-11
      • 2011-12-20
      • 2019-08-18
      • 2019-03-08
      • 1970-01-01
      相关资源
      最近更新 更多