Rails Google Client API - 无法为访问令牌交换刷新令牌

时间:2012-09-24 20:51:06

标签: ruby-on-rails oauth-2.0 omniauth access-token google-api-client

在我的计算机上遇到某些SSL issues之后,我仍然试图通过Google Ruby Client API访问用户的Blogger帐户。我正在使用以下内容:

  • Rails 3.2.3
  • Ruby 1.9.3
  • oauth2(0.8.0)
  • omniauth(1.1.1)
  • omniauth-google-oauth2(0.1.13)
  • google-api-client(0.4.6)

我可以在身份验证时通过Google API成功验证用户身份并访问他们的博客。当用户登录时,我会存储从Google收到的access_tokenrefresh_token。一切都很好,直到access_token到期。我正在尝试构建为新refresh_token交换access_token的功能,但不断遇到问题。以client documentation为例,这是我正在使用的代码:

  client = Google::APIClient.new
  token_pair = auth.oauth_token   # access_token and refresh_token received during authentication

  # Load the access token if it's available
  if token_pair  
    client.authorization.update_token!(token_pair.to_hash)
  end            

  # Update access token if expired
  if client.authorization.refresh_token && client.authorization.expired?
    client.authorization.fetch_access_token!
  end

  blogger = client.discovered_api('blogger', 'v3')
  result = client.execute(
      api_method: blogger.blogs.list_by_user,
      parameters: {'userId' => "self", 'fields' => 'items(description,id,name,url)'},
      headers: {'Content-Type' => 'application/json'})

此代码在access_token有效时完美运行。一旦它到期,我就会看到两个问题:

  1. 即使我知道令牌已过期(我已在数据库中检查expires_at值),client.authorization.expired?返回false - 我是否有不同的方法可以检查到期日期除了使用数据库中的值之外还有令牌吗?
  2. 当我强制执行client.authorization.fetch_access_token!时,我收到invalid_request错误。
  3. 有人可以告诉我如何使用客户端API与新refresh_token交换access_token吗?即使你知道如何用另一种语言来做,这将是一个很大的帮助,因为我可以尝试Rubyfy它。谢谢!

3 个答案:

答案 0 :(得分:25)

您可能已经发现了这一点,但您可以在google阅读整个过程:https://developers.google.com/accounts/docs/OAuth2WebServer

omniauth-google-oauth2策略已经负责设置access_type和approval_prompt,因此获取刷新令牌只需使用grant_type = request_token

发布到https://accounts.google.com/o/oauth2/token

这是大致我使用的代码:

def refresh_token
  data = {
    :client_id => GOOGLE_KEY,
    :client_secret => GOOGLE_SECRET,
    :refresh_token => REFRESH_TOKEN,
    :grant_type => "refresh_token"
  }
  @response = ActiveSupport::JSON.decode(RestClient.post "https://accounts.google.com/o/oauth2/token", data)
  if @response["access_token"].present?
    # Save your token
  else
    # No Token
  end
rescue RestClient::BadRequest => e
  # Bad request
rescue
  # Something else bad happened
end

答案 1 :(得分:16)

由于您使用的是Ruby Google API客户端,为什么不使用它来交换刷新令牌呢? Ruby API在内部做了几乎相同的事情,@ brimil01在他的回答中说过。

这就是我使用Ruby API交换刷新令牌以获取新访问令牌的方法。

def self.exchange_refresh_token( refresh_token )
  client = Google::APIClient.new
  client.authorization.client_id = CLIENT_ID
  client.authorization.client_secret = CLIENT_SECRET
  client.authorization.grant_type = 'refresh_token'
  client.authorization.refresh_token = refresh_token

  client.authorization.fetch_access_token!
  client.authorization
end

根据this issue here,建议不要使用expired?方法检查访问令牌是否已过期。

  

基本上,不要拨打过期的电话吗?方法。基本上为零   这是一个好主意的场景。它根本不会给你可靠的   到期信息。它更多的是暗示而不是真正的过期   时间戳,令牌服务器可以决定兑现过期的令牌   无论如何,在某些理论上,但重要的情况下。   如果确实收到无效授权错误,请始终刷新访问令牌   并重试一次。如果您仍然收到错误,请提出错误。

这就是我的工作。

# Retrieved stored credentials for the provided user email address.
#
# @param [String] email_address
#   User's email address.
# @return [Signet::OAuth2::Client]
#  Stored OAuth 2.0 credentials if found, nil otherwise.
def self.get_stored_credentials(email_address)
  hash = Thread.current['google_access_token']
  return nil if hash.blank?

  hash[email_address]
end

##
# Store OAuth 2.0 credentials in the application's database.
#
# @param [String] user_id
#   User's ID.
# @param [Signet::OAuth2::Client] credentials
#   OAuth 2.0 credentials to store.
def self.store_credentials(email_address, credentials)
  Thread.current['google_access_token'] ||= {}
  Thread.current['google_access_token'][email_address] = credentials
end


def self.credentials_expired?( credentials )
  client = Google::APIClient.new
  client.authorization = credentials
  oauth2 = client.discovered_api('oauth2', 'v2')
  result = client.execute!(:api_method => oauth2.userinfo.get)

  (result.status != 200)
end


# @return [Signet::OAuth2::Client]
#  OAuth 2.0 credentials containing an access and refresh token.
def self.get_credentials
  email_address = ''

  # Check if a valid access_token is already available.
  credentials = get_stored_credentials( email_address )
  # If not available, exchange the refresh_token to obtain a new access_token.

  if credentials.blank?
    credentials = exchange_refresh_token(REFRESH_TOKEN)
    store_credentials(email_address, credentials)
  else
    are_credentials_expired = credentials_expired?(credentials)

    if are_credentials_expired
      credentials = exchange_refresh_token(REFRESH_TOKEN)
      store_credentials(email_address, credentials)
    end
  end

  credentials
end

答案 2 :(得分:0)

我用下面的简单代码修复了它。

   def refesh_auth_tooken(refresh_token) 
       client = Google::APIClient.new 
       puts "REFESH TOOKEN"
       client.authorization = client_secrets
       client.authorization.refresh_token = refresh_token

       #puts YAML::dump(client.authorization)

       client.authorization.fetch_access_token!
       return client.authorization

     end