I have a custom dashboard in Ruby on Rails project with data collected from Google Analytics. I user Google Analytics Reporting V4 API and a Service Account to authenticate.
My code works well if I don't impersonate user authorization.sub = 'xxx@mail.com'
and If I do it, I get unauthorized_client
error but not all the times. Sometimes it works, and sometimes not.
This is my code:
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 server log output:
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."
}):
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…