无法使用服务帐户令牌生成Google Analytics(分析)DataChart客户端(无效凭据错误)

时间:2018-11-06 16:32:37

标签: javascript c# google-analytics google-analytics-api google-analytics-v4

我正尝试通过其Javascript API实现 Google Analytics(分析)图,例如其网站link上的示例。

但是每次我尝试执行 gapi.analytics.googleCharts.DataChart

时,我都会不断收到 “ 401无效凭证”

我使用以下代码获取访问令牌服务器端(C#),其中包含为服务帐户生成的JSON数据

var cred = new ServiceAccountCredential(
    new ServiceAccountCredential.Initializer(clientId)
    {
        Scopes = new[] { AnalyticsReportingService.Scope.AnalyticsReadonly },
        User = clientEmail,
        ProjectId = "projectID"
    }.FromPrivateKey(privateKey));

var token = cred.GetAccessTokenForRequestAsync(authURI);
token.Wait();
var result = token.Result;
return result;

或(使用完整的json字符串,另请参见注释)

GoogleCredential cred;

var gCred = GoogleCredential.FromJson(json).UnderlyingCredential as
    ServiceAccountCredential;

var token = gCred.GetAccessTokenForRequestAsync("https://accounts.google.com/o/oauth2/auth");
return token.Result;

客户端

gapi.analytics.auth.authorize({
    'serverAuth': {
      'access_token': '{{ ACCESS_TOKEN_FROM_SERVICE_ACCOUNT }}'
    }
  });

使用并使用 gapi.analytics.auth.isAuthorized()会使用任何服务器端函数返回true,但在尝试调用时会失败

  var dataChart1 = new gapi.analytics.googleCharts.DataChart(queryJson);
  dataChart1.execute();

返回401“无效凭据”,服务器端查询返回的值很好,所以我认为用户权限不是问题

注意:使用与第二个代码相同的代码(使用json字符串生成凭据而不将其转换为ServiceAccountCredential),我可以从API服务器端获取数据

cred = gCred.CreateScoped(scopes);

using (var reportingService = new AnalyticsReportingService(new BaseClientService.Initializer
    {
        HttpClientInitializer = cred
    }))
...
var getReportsRequest = new GetReportsRequest
{
    ReportRequests = new List<ReportRequest> { reportRequest }
};
var batchRequest = reportingService.Reports.BatchGet(getReportsRequest);

var response = batchRequest.Execute(); //This returns a response object with all the data I need

1 个答案:

答案 0 :(得分:0)

如果有人遇到相同的问题:

您需要使用 GoogleCredential.GetApplicationDefault() 创建凭据对象,对于Google Analytics(分析),您应该获得类似的信息

var credential = GoogleCredential.GetApplicationDefault().CreateScoped(AnalyticsReportingService.Scope.AnalyticsReadonly);

这将从Windows上的环境变量获取json文件,因此您需要将 GOOGLE_APPLICATION_CREDENTIALS 设置为json的路径作为系统变量。

初始化服务并设置服务变量

using (var reportingService = new AnalyticsReportingService(new BaseClientService.Initializer { HttpClientInitializer = credential }))
{
  var serviceCredential = cred.UnderlyingCredential as ServiceAccountCredential;
}