0

I use OAuth2::Client for get access_token. Need refresh it with refresh_token

client_id = '95585XXXXXXXoogleercontent.com'
secret_key = 'R10Ze490IYa'
client = OAuth2::Client.new(client_id, secret_key, {
  authorize_url: 'https://accounts.google.com/o/oauth2/auth',
  token_url: 'https://accounts.google.com/o/oauth2/token'
})


redirect_url = client.auth_code.authorize_url({
  scope: 'https://www.googleapis.com/auth/analytics.readonly',
  redirect_uri: 'https://example.com',
  access_type: 'offline'
})

auth_code = '4/5AF6VI0JMcmA38XXXXX' # getted from redirect_url clicking 

access_token = client.auth_code.get_token(auth_code, redirect_uri: 'https://example.com')

Then I try to refresh token:

access_token.refresh!

And I have error:

RuntimeError: A refresh_token is not available

Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449
mpz
  • 1,906
  • 3
  • 15
  • 23

1 Answers1

0

Need add - prompt: 'consent':

  redirect_url = client.auth_code.authorize_url({
    scope: 'https://www.googleapis.com/auth/analytics.readonly',
    redirect_uri: 'https://example.com',
    access_type: 'offline',
    prompt: 'consent'
  })

Then you can get new access_token:

new_access_token = access_token.refresh!

Also you can save token for future using:

hash = access_token.to_hash  # save it
# load:
loaded_token = OAuth2::AccessToken.from_hash(client, hash)
mpz
  • 1,906
  • 3
  • 15
  • 23
  • 1
    The refresh token is not returned every time with some languages / libraries it is only returned the first time. By sending prompt consent you are forcing the user to re-authorize (by showing the consent screen) your application. Once you have a refresh token stored for your user you should not need to use prompt consent. – Linda Lawton - DaImTo Oct 12 '20 at 05:28