Skip to content

Make it possible to use sub-strategies to get offline unexpired access tokens #185

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

mrj
Copy link

@mrj mrj commented Aug 9, 2025

Do people use omniauth-oauth2 sub-strategies to instantiate, and possibly refresh, access tokens from tokens saved from the authorization flow (offline access), or do they directly instantiate oauth2 Client and AccessToken classes? If the latter, it seems to me that much of the work done by, and settings in, the strategies must be duplicated, especially the various options.

This PR adds a refresh_access_token method that encapsulates the same token_params and options.auth_token_params settings as used in getting the access token during the authorization flow. This is now also called when the token is already expired when obtained. Does this happen?

A set_access_token_from_hash utility method is also added so that the common requirement of setting the access token from a saved hash needs less code.

Example code to generate an unexpired access token from saved access and refresh tokens becomes:

strategy = OmniAuth::Strategies::Tiktok.new(nil, <tiktok_client_id>, <tiktok_client_secret>, client_options: { raise_errors: false })

# The duplication above of the client_id and client_secret from omniauth.rb is unfortunate.
# Hopefully OmniAuth will support access to their strategy instances: e.g.
# strategy = OmniAuth.get_strategy('tiktok')

strategy.set_access_token_from_hash access_token: <from DB>, refresh_token: <from DB>

if <access token has expired>
  strategy.refresh_access_token
  if strategy.access_token.token
    <save updated token to DB>
  else
    return false
  end
end

strategy.access_token

An alternative is a strategy.get_unexpired_access_token_from_hash method that incorporates the code above, with a good way to detect a refreshed token so it can be saved.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant