我在我的rails应用程序上运行了omniauth-oauth2子类策略。何时刷新access_token,我发现我需要创建OAuth2::AccessToken
。但要创建它,它似乎需要OAuth2::Client
我认为可以从“omniauth-oauth2子类策略”中获得。
找到了这个解决方案Refresh token using Omniauth-oauth2 in Rails application 这就是他们如何解决以获得战略
# the initial param:nil is meant to be a rack object, but since
# we don't use it here, we give it a nil
strategy = OmniAuth::Strategies::YOUR_PROVIDER.new nil, client_id, client_secret
client = strategy.client
your_expired_at_from_your_provider = Time.now.to_i
hash = {
access_token: "your access_token from your provider",
refresh_token: "your refresh_token from your provider",
expires_at: your_expired_at_from_your_provider,
}
access_token_object = OAuth2::AccessToken.from_hash(client, hash)
access_token_object.refresh!
https://github.com/omniauth/omniauth/blob/v1.6.1/lib/omniauth/strategy.rb#L132 https://github.com/intridea/omniauth-oauth2/blob/v1.4.0/lib/omniauth/strategies/oauth2.rb#L35 https://github.com/intridea/oauth2/blob/master/lib/oauth2/access_token.rb#L12 https://github.com/intridea/oauth2/blob/v1.4.0/lib/oauth2/access_token.rb#L82
我不明白的是,通过将nil
提供给第一个参数来创建策略看起来有点愚蠢。
创建像上面这样的策略是刷新令牌的唯一方法吗?
strategy -> client -> access_token_object -> refresh!
答案 0 :(得分:1)
我找不到正确的方法,但是为我的自定义omniauth策略提供了一种解决方法:
class MyOrg < OmniAuth::Strategies::OAuth2
#...
info do
{
'email' => extra['user'].try(:[], 'email'),
# ...
'get_org' => Proc.new do
get_org
end
}
end
def get_org
@org ||= begin
org_id = extra['user'].try(:[], 'org_id')
access_token.get(options[:client_options][:site] + "/v1/orgs/#{org_id}").parsed
end
end
end
然后将其称为:
hash[:info][:get_org].call
答案 1 :(得分:-1)
我利用oauth2
宝石进行刷新。这是使用omniauth策略访问google API的完整解决方案:https://stackoverflow.com/a/57191048/2672869