【问题标题】:Google analytics reporting authorize service account谷歌分析报告授权服务帐户
【发布时间】: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


    【解决方案1】:

    这是我通常用来验证服务的代码。 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 drive 帐户 google calendar,可能还有更多。他们默认没有的是谷歌分析帐户。

    “用户没有谷歌分析帐户 403 被禁止”。

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

    您需要登录到网络版的谷歌分析,然后转到您希望服务帐户访问的网站的管理部分。将服务帐户电子邮件地址添加为帐户级别的用户。

    【讨论】:

    • 现在异常显示“用户没有谷歌分析帐户 403 frobidden”。我已经在 google api 控制台中创建了服务帐户
    • 检查我的更新。仅仅因为您在 Google Developer Console 中创建了服务帐户并不意味着它可以访问任何数据。您需要授予它访问权限。这就是预先批准服务帐户的方式。
    • 谢谢,服务账号的配置忘记了
    猜你喜欢
    • 2012-11-15
    • 1970-01-01
    • 2021-11-10
    • 2019-05-23
    • 2013-01-09
    • 1970-01-01
    • 2019-05-10
    • 2021-10-21
    • 1970-01-01
    相关资源
    最近更新 更多