当我从终端调用它时,以下代码行正常工作。我想在我的Rails应用程序中运行相当于它来刷新我的access_token字段(参见Using the Access and Refresh Tokens):
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
假设我有所有可用的参数,我将如何从模型或控制器发布此请求?
答案 0 :(得分: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
答案 1 :(得分: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}"))