我在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."
}):
答案 0 :(得分:2)
请记住,服务帐户是虚拟用户。要使服务帐户能够访问您的Google Analytics(分析)帐户,需要预先授权。您可以像对待任何其他用户一样授权服务帐户。您需要通过Google Analytics网站以用户身份添加服务帐户,您需要在ACCOUNT级别将其添加到帐户级别。
就模仿而言,我不确定我理解你在做什么。我不是ruby dev,但是你的代码看起来不像我找到的样本here。