【问题标题】:OAuth request to Google succeeds locally, but fails with "invalid_grant" on Heroku对 Google 的 OAuth 请求在本地成功,但在 Heroku 上因“invalid_grant”而失败
【发布时间】:2014-07-12 05:12:17
【问题描述】:

我正在使用 Google 服务帐号为我的 Dashing 仪表板向 Google Analytics(分析)发出 API 调用。我正在使用 Legato gem 来获取 Analytics 数据,并使用 gem 的 wiki 的 instructions for service accounts 进行身份验证。

我已将我的 Google 用户名和私钥放入 ENV(在对其进行 base 64 编码之后),并使用 dotenv 在本地和 Heroku 之间同步这些设置(heroku config 确认一切设置正确)。所以,我的验证码是这样的:

class GoogleAnalyticsAccount
  attr_accessor :user, :profile

  # Thanks to the "Service Accounts" section at
  # https://github.com/tpitale/legato/wiki/OAuth2-and-Google
  def initialize scope="https://www.googleapis.com/auth/analytics.readonly"
    client = Google::APIClient.new application_name: '[App name]',
                                   application_version: '1.0'

    key = Google::APIClient::PKCS12.load_key(Base64.decode64(ENV['GOOGLE_PRIVATE_KEY_BASE64']), "notasecret")

    service_account = Google::APIClient::JWTAsserter.new(ENV['GOOGLE_USER'], scope, key)

    client.authorization = service_account.authorize

    oauth_client = OAuth2::Client.new("", "", {
       :authorize_url => 'https://accounts.google.com/o/oauth2/auth',
       :token_url => 'https://accounts.google.com/o/oauth2/token'
    })
    token = OAuth2::AccessToken.new(oauth_client, client.authorization.access_token)
    @user = Legato::User.new(token)
  end

  def profile
    @user.profiles.first
  end
end

在本地,此代码运行良好。在 Heroku 上,我收到了来自 Google 的以下回复:

{
  "error": "invalid_grant"
}

没有比这更详细的了。基于广泛的谷歌搜索,我发现这两个最可能的原因是 A)我已经达到了我的请求限制(但不可能是这样,因为相同的凭据在本地工作)和 B)服务器时钟未与 NTP 同步。我已将 Heroku 上的时区设置为 America/Chicago(与我的本地机器相同),但没有骰子。

有什么想法吗?谢谢!

【问题讨论】:

    标签: ruby heroku oauth google-analytics google-api-client


    【解决方案1】:

    嗯。我使用 dotenv 和 heroku-config 将我的设置推送到 Heroku。事实证明,将我的 GOOGLE_USER 和 GOOGLE_PRIVATE_KEY_BASE64 放在我的 .env 文件中的引号内是由 heroku-config 逐字逐句获取的,它会将这些设置带引号推送到我的 Heroku 配置中。因此,用户名/密钥无效——因此是invalid_grant

    想想我已经解决这个问题好几天了......

    【讨论】:

      猜你喜欢
      • 2020-10-19
      • 2023-01-17
      • 2022-09-30
      • 2013-01-29
      • 2019-06-30
      • 2020-11-12
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      相关资源
      最近更新 更多