我最终在我的身份验证模型中实现了以下代码,以获取刷新的 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