【发布时间】:2018-04-13 10:15:59
【问题描述】:
我正在尝试使用谷歌分析 API 来使用服务帐户在 c# webapp 中报告用户信息。
我已下载 JWT 文件并将其链接到项目中。
我在尝试验证服务帐户时遇到问题:当我调用 RequestAccessTokenAsync(cancellationToken) 时抛出异常说 Scope 不能为空值,我无法设置 Scope 因为我正在创建 @987654322 @来自 json 流。
另一种方法是使用serviceAccountCredential.GetAccessTokenForRequestAsync(serviceAccountCredential.TokenServerUrl) 请求访问令牌,但在这种情况下,我不明白如何将该令牌提供给报告请求,如果没有该令牌,API 调用将不会被授权并且会失败。
这是源代码:
string viewId = "VIEW_ID";
FileStream jwtSecretStream = new FileStream(@"path\to\servicesecret.json", FileMode.Open, FileAccess.Read);
var metrics = new List<Metric> { new Metric { Expression = "ga:users" } };
var dimensions = new List<Dimension> { new Dimension { Name = "ga:userType" } };
DateRange dateRange = new DateRange
{
StartDate = DateTime.UtcNow.AddDays(-7).ToString("yyyy-MM-dd"),
EndDate = DateTime.UtcNow.ToString("yyyy-MM-dd")
};
try
{
serviceAccountCredential = ServiceAccountCredential.FromServiceAccountData(jwtSecretStream);
// this call will throw the exception
var x = await serviceAccountCredential.RequestAccessTokenAsync(CancellationToken.None);
//this call will return a valid token -> DON'T KNOW HOW TO PASS To THE REQUEST
//var y = await serviceAccountCredential.GetAccessTokenForRequestAsync(serviceAccountCredential.TokenServerUrl);
}
catch (Exception e)
{
throw;
}
_analyticsReportingService = new AnalyticsReportingService(new AnalyticsReportingService.Initializer()
{
HttpClientInitializer = serviceAccountCredential,
//HttpClientInitializer = credential,
ApplicationName = "TestAnalytics",
});
//If I execute the request I got UNAUTHORIZED because there's not a valid access token
var response = _analyticsReportingService.Reports.BatchGet(getReportRequest).Execute();
如何为服务帐户提供有效范围,或者请求访问令牌并将其放入批处理请求中?
【问题讨论】:
标签: c# .net google-api google-analytics-api google-api-dotnet-client