【问题标题】:Client is unauthorized to retrieve access tokens using this method客户端未经授权使用此方法检索访问令牌
【发布时间】:2017-02-06 12:02:57
【问题描述】:

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

【问题讨论】:

标签: ruby-on-rails google-analytics google-api google-analytics-api service-accounts


【解决方案1】:

请记住,服务帐户是虚拟用户。要使服务帐户能够访问您的谷歌分析帐户,它需要预先授权。您像授权任何其他用户一样授权服务帐户。您需要通过 Google Analytics 网站将服务帐户添加为用户,您需要在 ACCOUNT 级别执行此操作,它必须是 ACCOUNT 级别。

我不确定我是否理解你在做什么,就冒充而言。我不是 ruby​​ 开发人员,但您的代码看起来不像我找到的示例 here。

【讨论】:

  • 问题是我无法为服务帐户用户授予对 Google Analytics 视图的读取权限。我不是管理员...我的问题是为什么它只出现有时,我该如何解决这个错误?也许谷歌开发者控制台中的一些配置?谢谢!
  • 服务帐户必须通过谷歌分析网站进行预授权,没有解决方法。如果您不是帐户的所有者,为什么要使用服务帐户,您应该使用 Oauth2 并请求所有者的访问权限。
  • 这可能有助于developers.google.com/api-client-library/ruby/guide/aaa_oauth 存储刷新令牌以便能够随时访问用户数据。
  • 如果我进行 OAuth2 身份验证,我需要在谷歌分析视图中为每个需要访问权限的用户提供读取权限,这不会发生。很难解释,但我需要进行服务帐户身份验证。我不是管理员,但我拥有所有其他权限。
  • 如果您使用 Oauth2,您需要为每个将使用您的应用程序的用户提供一个刷新令牌。刷新令牌将使您能够访问所有谷歌分析帐户,表示用户有权访问您不需要每个谷歌分析视图。除非您可以联系每个用户并让他们授予您的服务帐户访问他们的谷歌分析帐户的权限,否则您不能使用服务帐户。您必须使用 oauth2
猜你喜欢
  • 2018-12-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-14
  • 2019-01-27
  • 2017-08-04
  • 2019-04-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多