本文介绍了在 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?

如果要编写自定义代码,helper 是否适合编写逻辑?

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

推荐答案

Omniauth 没有提供开箱即用的功能,所以我使用了之前的答案和另一个 SO 答案在我的模型 User.js 中编写代码.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 刷新令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 06:12