0

当我从终端调用以下代码行时,它可以正常工作。我想在我的 Rails 应用程序中运行它的等效项来刷新我的 access_token 字段(请参阅使用访问和刷新令牌):

curl https://api.box.com/oauth2/token \
-d 'grant_type=refresh_token&refresh_token={valid refresh token}&client_id={your_client_id}&client_secret={your_client_secret}' \
-X POST

假设我有所有可用的参数,我将如何从模型或控制器发布此请求?

4

2 回答 2

1

我最终在我的身份验证模型中实现了以下代码,以获取刷新的 Box OAuth 令牌。这样我就可以做一些事情,比如User.authentication.find_by_provider('box').refresh!它是否过期(我每次通过该token方法调用 Box API 时都会检查它)。

  require 'uri'
  require 'net/http'

  def refresh!
    case self.provider
    when 'box'
      url = "https://api.box.com/oauth2/token"
      uri = URI(url)
      params = {}
      params["grant_type"] = "refresh_token"
      params["refresh_token"] = self.refresh_token
      params["client_id"] = APP_CONFIG['box_client_id']
      params["client_secret"] = APP_CONFIG['box_client_secret']
      res = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
               req = Net::HTTP::Post.new(uri.path)
               req.set_form_data(params)
               response = http.request(req)
            end
      res_json = JSON.parse(res.body)
      self.refresh_token = res_json["refresh_token"]
      self.oauth_token = res_json["access_token"]
      self.expires_at = Time.now.to_i + res_json["expires_in"].to_i
      self.save      
    end
  end

  def fresh_token
    case self.provider
    when 'box'
      self.refresh! if self.is_expired? && self.is_refreshable?
      self.oauth_token
    else
      self.oauth_token
    end
  end


  def is_refreshable?
    case self.provider
    when 'box'
      Time.now < self.updated_at + 14.days ? true : false
    else
      nil
    end
  end


  def is_expired?
    case self.provider
    when 'box'
      Time.now.to_i > self.expires_at ? true : false
    else
      false      
    end
  end

例如,要获取 Box 用户配置文件,我会这样做:

  def profile
    token = self.fresh_token

    case self.provider
    when 'box'
      profile = JSON.parse(open("https://api.box.com/2.0/users/me?access_token=#{token}").read)
    end
  end
于 2013-02-05T02:17:22.980 回答
0
Net::HTTP.post_form(URI.parse("https://api.box.com/oauth2/token?grant_type=refresh_token&refresh_token=#{valid_refresh_token}&client_id=#{your_client_id}&client_secret=#{your_client_secret}"))
于 2013-02-04T23:51:30.100 回答