El cliente no está autorizado para recuperar tokens de acceso utilizando este método

Tengo un panel personalizado en el proyecto Ruby on Rails con datos recopilados de Google Analytics. Utilizo la API de Google Analytics Reporting V4 y una cuenta de servicio para autenticar.

Mi código funciona bien si no me hago pasar por el usuarioauthorization.sub = '[email protected]' y si lo hago, me saleunauthorized_client error pero no todas las veces. A veces funciona, y a veces no.

Este es mi código:

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 = '[email protected]'

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)

Salida del registro del servidor 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."
}):

Respuestas a la pregunta(1)

Su respuesta a la pregunta