谷歌OAuth访问令牌

6
我对OAuth和Google感到非常困惑。我花了很长时间才得到refresh_token以创建新的access_token。然后发现refresh_token也会过期??这有什么意义!!?
我只需要持久化一个有效的access_token,以便与legato一起使用。
以下是我手动输入到终端以检索OAUTH代码的内容:
client = OAuth2::Client.new('GA_CLIENT_ID', 'GA_SECRET_KEY', {
        :authorize_url => 'https://accounts.google.com/o/oauth2/auth',
        :token_url => 'https://accounts.google.com/o/oauth2/token'
})
client.auth_code.authorize_url({
       :scope => 'https://www.googleapis.com/auth/analytics.readonly',
       :redirect_uri => 'http://localhost',
       :access_type => 'offline',
       :approval_prompt=> 'force'
}) 

然后我手动在浏览器中输入输出的url。我将返回的OAUTH代码导出为环境变量并获取访问令牌:

access_token = client.auth_code.get_token(ENV['GA_OAUTH_CODE'], :redirect_uri => 'http://localhost')

然后我就可以访问access_token和refresh_token:

   begin
      api_client_obj = OAuth2::Client.new(ENV['GA_CLIENT_ID'], ENV['GA_SECRET_KEY'], {:site => 'https://www.googleapis.com'})
      api_access_token_obj = OAuth2::AccessToken.new(api_client_obj, ENV['GA_OAUTH_ACCESS_TOKEN'])
      self.user = Legato::User.new(api_access_token_obj)
      self.user.web_properties.first # this tests the access code and throws an exception if invalid
    rescue Exception => e
      refresh_token
    end

  end

  def refresh_token
    refresh_client_obj =  OAuth2::Client.new(ENV['GA_CLIENT_ID'], ENV['GA_SECRET_KEY'], {
            :authorize_url => 'https://accounts.google.com/o/oauth2/auth',
            :token_url => 'https://accounts.google.com/o/oauth2/token'
        })
    refresh_access_token_obj = OAuth2::AccessToken.new(refresh_client_obj, ENV['GA_OAUTH_ACCESS_TOKEN'], {refresh_token: ENV['GA_OAUTH_REFRESH_TOKEN']})
    refresh_access_token_obj.refresh!
    self.user = Legato::User.new(refresh_access_token_obj)
  end

一个小时后,我的令牌就会过期,我必须从浏览器手动重新开始这个过程!我如何在代码中复制这个过程?

我想你还没有找到答案。我也遇到了同样的问题。 - juanpaco
我还没有,但我相信解决方案涉及使用回调函数。我在这里打开了一个更具体的问题:http://stackoverflow.com/questions/16864199/how-to-configure-route-for-oauth-callback/16923267?noredirect=1#16923267。我还没有试过提交的答案。 - mnort9
1个回答

3

这里有一些专门为你准备的简单实现,旨在方便更新令牌。

请确保:

  1. 输入你自己的 APP_IDAPP_SECRET
  2. 要么只保存你的 refresh_token 并在每次使用前调用 refresh_token(),要么每次使用时都使用 refresh_token_if_needed(),并重新保存 tokenexpires_at(显然更好,因为只有在需要刷新时才会刷新)。
  3. 让我知道它的效果如何。

.

require 'gmail'
require 'gmail_xoauth'
require 'httparty'

class GmailManager
  APP_ID      = "DDDDDDDDDDDD-SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS.apps.googleusercontent.com"
  APP_SECRET  = "SSSSSS-SSSSSSSSSSSSSSSSS"

  def refresh_token(refresh_token)
    Rails.logger.info "[GmailManager:refresh_token] refreshing using this refresh_token: #{refresh_token}"
    # Refresh auth token from google_oauth2 and then requeue the job.
    options = {
      body: {
        client_id:     APP_ID,
        client_secret: APP_SECRET,
        refresh_token: refresh_token,
        grant_type:    'refresh_token'
      },
      headers: {
        'Content-Type' => 'application/x-www-form-urlencoded'
      }
    }
    response = HTTParty.post('https://accounts.google.com/o/oauth2/token', options)
    if response.code == 200
      token = response.parsed_response['access_token']
      expires_in = DateTime.now + response.parsed_response['expires_in'].seconds
      Rails.logger.info "Success! token: #{token}, expires_in #{expires_in}"
      return token, expires_in
    else
      Rails.logger.error "Unable to refresh google_oauth2 authentication token."
      Rails.logger.error "Refresh token response body: #{response.body}"
    end
    return nil, nil
  end

  def refresh_token_if_needed(token, expires_on, refresh_token)
    if token.nil? or expires_on.nil? or Time.now >= expires_on
      Rails.logger.info "[GmailManager:refresh_token_if_needed] refreshing using this refresh_token: #{refresh_token}"
      new_token, new_expires_on = self.refresh_token(refresh_token)
      if !new_token.nil? and !new_expires_on.nil?
        return new_token, new_expires_on
      end
    else
      Rails.logger.info "[GmailManager:refresh_token_if_needed] not refreshing. using this token: #{token}"
    end
    return token, expires_on
  end
end

谢谢。我拿了你的代码并将其制作成了一个不错的类:https://gist.github.com/Overbryd/0ae6287b02a9848e5b67 - Overbryd

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接