Google 分析报告授权服务帐户

Google analytics reporting authorize service account

我正在尝试使用 google 分析 API 在使用服务帐户的 c# webapp 中报告用户信息。

我已经下载了 JWT 文件并将其链接到项目中。 我在尝试验证服务帐户时遇到问题:当我调用 RequestAccessTokenAsync(cancellationToken) 时抛出 anc 异常,说范围不能为空值,我无法设置范围,因为我正在创建serviceAccountCredential 来自 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();

如何为服务帐户提供有效范围,或者请求访问令牌并将其放入批处理请求中?

这是我通常用来验证服务的代码。 Serviceaccount.cs

/// <summary>
    /// Authenticating to Google using a Service account
    /// Documentation: https://developers.google.com/accounts/docs/OAuth2#serviceaccount
    /// </summary>
    /// <param name="serviceAccountEmail">From Google Developer console https://console.developers.google.com</param>
    /// <param name="serviceAccountCredentialFilePath">Location of the .p12 or Json Service account key file downloaded from Google Developer console https://console.developers.google.com</param>
    /// <returns>AnalyticsService used to make requests against the Analytics API</returns>
    public static AnalyticsreportingService AuthenticateServiceAccount(string serviceAccountEmail, string serviceAccountCredentialFilePath, string[] scopes)
    {
        try
        {
            if (string.IsNullOrEmpty(serviceAccountCredentialFilePath))
                throw new Exception("Path to the service account credentials file is required.");
            if (!File.Exists(serviceAccountCredentialFilePath))
                throw new Exception("The service account credentials file does not exist at: " + serviceAccountCredentialFilePath);
            if (string.IsNullOrEmpty(serviceAccountEmail))
                throw new Exception("ServiceAccountEmail is required.");                

            // For Json file
            if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".json")
            {
                GoogleCredential credential;
                using (var stream = new FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read))
                {
                    credential = GoogleCredential.FromStream(stream)
                         .CreateScoped(scopes);
                }

                // Create the  Analytics service.
                return new AnalyticsreportingService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Analyticsreporting Service account Authentication Sample",
                });
            }
            else if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".p12")
            {   // If its a P12 file

                var certificate = new X509Certificate2(serviceAccountCredentialFilePath, "notasecret", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
                var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
                {
                    Scopes = scopes
                }.FromCertificate(certificate));

                // Create the  Analyticsreporting service.
                return new AnalyticsreportingService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Analyticsreporting Authentication Sample",
                });
            }
            else
            {
                throw new Exception("Unsupported Service accounts credentials.");
            }

        }
        catch (Exception ex)
        {                
            throw new Exception("CreateServiceAccountAnalyticsreportingFailed", ex);
        }
    }
}

服务帐户奖励信息

服务帐户是虚拟用户。默认情况下,他们有自己的 google 驱动器帐户 google 日历,可能还有更多。默认情况下,他们没有 Google Analytics 帐户。

"The user don't have a google analytics account 403 forbidden".

当用户尝试访问 Google 分析 api 但实际上没有访问任何 google 分析帐户时,就会出现此消息。

您需要登录网页版 google analytics 转到您希望服务帐户访问的网站的管理部分。在帐户级别将服务帐户电子邮件地址添加为用户。