繁体   English   中英

从 Web 应用程序授权 Google 分析数据

[英]Authorize Google analytics data from a web application

我正在尝试将 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"];
    });

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

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

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

希望这对其他人有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM