Reputation: 2207
I have an omniauth-oauth2 subclass strategy working on my rails app. When to refresh access_token, I see I need to create OAuth2::AccessToken
. But to create it, it seems it requires OAuth2::Client
which I think can obtain from "omniauth-oauth2 subclass strategy."
found this solution Refresh token using Omniauth-oauth2 in Rails application This is how they solved to obtain a strategy
# 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
What I don't understand is, it looks a bit of hacky ways to create a strategy by giving nil
to the first argument.
"omniauth-oauth2 subclass strategy" is in rack (like the image below), so I am thinking there is a way to access to a strategy from rack middleware, somewhere?
Is creating a strategy like above is the only way to refresh token?
strategy -> client -> access_token_object -> refresh!
Upvotes: 3
Views: 1486
Reputation: 1454
I leveraged the oauth2
gem to do the refreshing. Here's a complete solution for using the omniauth strategy to access the google APIs: https://stackoverflow.com/a/57191048/2672869
Upvotes: -1
Reputation: 5126
I could not find a right way, but make a workaround for my custom omniauth strategy:
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
Then call it as:
hash[:info][:get_org].call
Upvotes: 1