Search code examples
rubyoauth-2.0google-oauthgmail-api

Ruby Oauth2 Signet Return token with refresh token


I am accessing gmail api. I am using ruby to get the access token. However, I need to get a refresh token with the access token. I am using signet as suggested here. https://readysteadycode.com/howto-access-the-gmail-api-with-ruby

The code looks like this

client = Signet::OAuth2::Client.new({
      client_id: ENV.fetch('GOOGLE_API_CLIENT_ID'),
      client_secret: ENV.fetch('GOOGLE_API_CLIENT_SECRET'),
      token_credential_uri: 'https://accounts.google.com/o/oauth2/token',
      redirect_uri: url_for(:action => :callback),
      code: params[:code]
    })
  
    // this is undefined
    refre_token = client.refresh_token

    response = client.fetch_access_token!

    access_token = response['access_token']

I tried adding additional parameters like this as suggested here

additional_parameters: {
    "access_type" => "offline",         # offline access
    "include_granted_scopes" => "true",  # incremental auth
  }

to the client.new call but did not seem to have any effect.

How do I get the refresh token from Signet::OAuth2?


Solution

  • The refresh token will only appear the first time you are authenticated.

    Follow these steps to remove the stored access so you can be authenticated like the first time.

    Manage your google account -> Security -> Manage 3rd party access -> your app name -> remove access

    Note: From my testing, it does not appear that the additional parameters property is necessary.