在Rails应用程序中使用Omniauth-oauth2刷新令牌 [英] Refresh token using Omniauth-oauth2 in Rails application

查看:130
本文介绍了在Rails应用程序中使用Omniauth-oauth2刷新令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在rails中使用omniauth-oauth2对支持oauth2的站点进行身份验证.完成oauth跳舞后,该站点向我提供了以下内容,然后将其保存到数据库中:

I am using omniauth-oauth2 in rails to authenticate to a site which supports oauth2. After doing the oauth dance, the site gives me the following, which I then persist into the database:

  1. 访问令牌
  2. Expires_AT(滴答声)
  3. 刷新令牌

是否有一个omniauth方法可以在令牌过期后自动刷新,还是应该编写自定义代码来做到这一点?

Is there an omniauth method to refresh the token automatically after it expires or should I write custom code which to do the same?

如果要编写自定义代码,那么助手是编写逻辑的正确地方吗?

If custom code is to be written, is a helper the right place to write the logic?

推荐答案

Omniauth不提供此功能,因此我使用了上一个答案和另一个SO答案在我的模型User.rb中编写代码

Omniauth doesn't offer this functionality out of the box so i used the previous answer and another SO answer to write the code in my model User.rb

def refresh_token_if_expired
  if token_expired?
    response    = RestClient.post "#{ENV['DOMAIN']}oauth2/token", :grant_type => 'refresh_token', :refresh_token => self.refresh_token, :client_id => ENV['APP_ID'], :client_secret => ENV['APP_SECRET'] 
    refreshhash = JSON.parse(response.body)

    token_will_change!
    expiresat_will_change!

    self.token     = refreshhash['access_token']
    self.expiresat = DateTime.now + refreshhash["expires_in"].to_i.seconds

    self.save
    puts 'Saved'
  end
end

def token_expired?
  expiry = Time.at(self.expiresat) 
  return true if expiry < Time.now # expired token, so we should quickly return
  token_expires_at = expiry
  save if changed?
  false # token not expired. :D
end

在使用访问令牌进行API调用之前,您可以调用如下方法,其中current_user是已登录的用户.

And before making the API call using the access token, you can call the method like this where current_user is the signed in user.

current_user.refresh_token_if_expired

确保安装 rest-client gem并在模型文件中添加require指令require 'rest-client' . ENV['DOMAIN']ENV['APP_ID']ENV['APP_SECRET']是可以在config/environments/production.rb(或开发)中设置的环境变量

Make sure to install the rest-client gem and add the require directive require 'rest-client' in the model file. The ENV['DOMAIN'], ENV['APP_ID'] and ENV['APP_SECRET'] are environment variables that can be set in config/environments/production.rb (or development)

这篇关于在Rails应用程序中使用Omniauth-oauth2刷新令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆