Google Analytics分析报告授权服务帐户

时间:2018-04-13 10:16:00

标签: c# .net google-api google-analytics-api google-api-dotnet-client

我尝试使用Google Analytics(分析)API使用服务帐户在c#webapp中报告用户信息。

我已经下载了JWT文件并将其链接到项目中。 我有一个问题,我尝试验证服务帐户:当我调用RequestAccessTokenAsync(cancellationToken) anc异常被抛出时,Scope不能是空值,我无法设置范围,因为我&# 39; m从json流创建serviceAccountCredential

另一种方法是使用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();

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

1 个答案:

答案 0 :(得分:2)

这是我通常用于验证服务的代码。 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 Analytics帐户。

  

&#34;用户没有禁止谷歌分析帐户403&#34;。

当用户尝试访问Google Analytics API并且实际上无法访问任何Google Analytics分析帐户时,会出现此消息。

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