Client is unauthorized to retrieve access tokens u

2019-01-27 04:52发布

问题:

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."
}):

回答1:

Remember that a service account is a dummy user. For a service account to be able to access your google analytics account it needs to be preauthorized. You authorize the service account just like you would any other user. You will need to add the service account as a user via the Google Analytics website you need to do this at the ACCOUNT level it must be the ACCOUNT level.

I am not sure I understand what you are doing as far as impersonation is going. I am not a ruby dev but your code doesn't look like the sample I found here.