【发布时间】:2017-02-06 12:02:57
【问题描述】:
我在 Ruby on Rails 项目中有一个自定义仪表板,其中包含从 Google Analytics 收集的数据。我使用 Google Analytics Reporting V4 API 和服务帐户进行身份验证。
如果我不冒充用户authorization.sub = 'xxx@mail.com',我的代码运行良好,如果我这样做,我会收到unauthorized_client 错误,但并非总是如此。有时有效,有时无效。
这是我的代码:
scope = [Google::Apis::AnalyticsreportingV4::AUTH_ANALYTICS_READONLY]
view_id = 'xxxxxx'
ENV['GOOGLE_APPLICATION_CREDENTIALS'] = "#{Rails.root}/private/google_analytics_key.json"
authorization = Google::Auth::get_application_default(scope)
authorization.sub = 'xxx@mail.com'
analytics = Google::Apis::AnalyticsreportingV4::AnalyticsReportingService.new
analytics.authorization = authorization
...
request = Google::Apis::AnalyticsreportingV4::GetReportsRequest.new(report_requests: report_requests)
@result = analytics.batch_get_reports(request)
Rails 服务器日志输出:
Sending HTTP post https://analyticsreporting.googleapis.com/v4/reports:batchGet?
Caught error Authorization failed. Server message:
{
"error": "unauthorized_client",
"error_description": "Client is unauthorized to retrieve access tokens using this method."
}
Error - #<Signet::AuthorizationError: Authorization failed. Server message:
{
"error": "unauthorized_client",
"error_description": "Client is unauthorized to retrieve access tokens using this method."
}>
Completed 500 Internal Server Error in 149ms (ActiveRecord: 0.4ms)
Signet::AuthorizationError (Authorization failed. Server message:
{
"error": "unauthorized_client",
"error_description": "Client is unauthorized to retrieve access tokens using this method."
}):
【问题讨论】:
-
authorization.sub 不支持 Google Analytics API 访问,因为 Analytics 不是 GSuite(工作应用)应用程序。
标签: ruby-on-rails google-analytics google-api google-analytics-api service-accounts