且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

客户端未经授权使用此方法检索访问令牌

更新时间:2022-10-15 14:18:47

请记住,服务帐户是虚拟用户。要使服务帐户能够访问您的Google Analytics帐户,需要预先授权。您授权服务帐户就像您对其他任何用户一样。您需要通过Google Analytics网站以用户身份添加服务帐户,您必须在帐户级别执行此操作,并且必须是帐户级别。



我不是当然,我明白你在模仿的过程中正在做什么。我不是Ruby开发者,但您的代码看起来不像我发现的样本这里

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

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.