我正在尝试将 ASP.NET Core 6 MVC 网络应用程序授权给 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 和密码以及添加环境变量。
为什么它不直接获取控制器运行时已经提供的授权?
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();
希望这对其他人有帮助。