[英]Equivalent of cURL Post request call in rails model or controller
The following line of code works fine when I call it from the terminal. 当我从终端调用时,以下代码行工作正常。 I want to run the equivalent of it from within my Rails app to refresh my access_token field (see Using the Access and Refresh Tokens ): 我想在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
Assuming I have all the params available, how would I post this request from a model or controller? 假设我有所有可用的参数,如何从模型或控制器发布此请求?
I ended up implementing the following code in my Authentication model to get a refreshed Box OAuth token. 我最终在身份验证模型中实现了以下代码,以获取刷新的Box OAuth令牌。 That way I can do something like User.authentication.find_by_provider('box').refresh!
这样,我可以执行类似User.authentication.find_by_provider('box').refresh!
if it's expired (which I check each time I call the Box API through the token
method). 是否已过期(每次我通过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
For instance, to get a Box user profile I would do: 例如,要获取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
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}"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.