1

我正在使用 Google API Ruby Client 获取对用户日历的访问权限。

我可以通过以下方式访问:

  client_id: "xxxxx"
  client_secret: "xxxxx"
  access_type: "offline"
  approval_type: ""
  scope: "https://www.google.com/calendar/feeds/ https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/calendar"
  callback_path: "/app/oauth_response"

  provider :google_oauth2, GOOGLE_API['client_id'], GOOGLE_API['client_secret'], 
            { access_type: GOOGLE_API['access_type'], 
              approval_prompt: GOOGLE_API['approval_prompt'], 
              scope: GOOGLE_API['scope'], 
              callback_path: GOOGLE_API['callback_path'],
              path_prefix: GOOGLE_API['path_prefix']}

当响应返回时,它有一个刷新令牌、访问令牌、expired_at 等。然后我可以使用访问代码发出 API 请求。但是一旦访问代码过期(一个小时后),我相信我需要使用刷新令牌来获取新的访问令牌,对吗?

这是我正在打的电话:

HTTParty.get('https://www.google.com/calendar/feeds/default/owncalendars/full', :query => {:alt => "jsonc", :access_token => access_token})

这告诉我我的令牌已过期。所以我试着买一个新的。但是当我尝试这样做时,我得到了这个:

@client.authorization.fetch_access_token!
ArgumentError Exception: Missing authorization code.

我在我的@client 对象@code=nil 中看到了这一点。我假设这是需要设置的,但我没有从我的初始请求中返回“代码”属性。

我如何获得该代码,或者如果我不需要它,我做错了什么?谢谢!

4

3 回答 3

3

很可能在您调用 fetch_access_token 时未在 @client.authorization 中设置刷新令牌!

看看https://github.com/google/signet/blob/master/lib/signet/oauth_2/client.rb

该错误消息仅在未知/未指定的 grant_type 中出现。grant_type 本身是根据授权客户端的状态推断出来的。

在您的用例中,尝试刷新令牌,它应该是“refresh_token”,如果设置了 refresh_token,grant_type 将返回该值。我的直觉是,如果您转储 @client.authorization.refresh_token 和 @client.authorization.grant_type 的值,它们都将为 nil。

解决方法是确保在调用该方法之前正确恢复 refresh_token。

于 2012-04-09T22:33:45.643 回答
0

Ruby 客户端库会在刷新令牌过期时自动从刷新令牌中获取新的访问令牌,因此您无需执行任何操作来处理这种情况。

于 2012-04-09T20:41:08.630 回答
0

在客户端有以下代码(https://github.com/google/signet/blob/621515ddeec1dfb6aef662cdfaca7ab30e90e5a1/lib/signet/oauth_2/client.rb#L935),所以你需要删除 aredirect_uri,当你不想获取访问令牌。

if self.redirect_uri
  # Grant type was intended to be `authorization_code` because of
  # the presence of the redirect URI.
  raise ArgumentError, 'Missing authorization code.'
end
于 2017-07-17T20:59:25.257 回答