0

I have a working app (Rails) that authenticates a user and saves her tokens in a Redis store.

If I've understood it correctly, using googleauth together with google-api-client, the client object will refresh the access token (by itself) as needed? This doesn't happen though, the token expires and some time after that I get a 403 error.

If the problem is on my side - can/should I invoke a new access_token manually, and if so how do I do that?

The code I've used is mainly taken from the quickstart guide.

gem 'google-api-client', require: 'google/apis/calendar_v3'

def authorizer
  scope = Google::Apis::CalendarV3::AUTH_CALENDAR
  client_id = Google::Auth::ClientId.from_hash(JSON.parse(ENV['GOOGLE_CLIENT_SECRETS']))
  token_store = Google::Auth::Stores::RedisTokenStore.new(redis: $redis)
  authorizer = Google::Auth::WebUserAuthorizer.new(client_id, scope, token_store)
  authorizer
end

def authenticate_the_user
  user_id = "1"
  credentials = authorizer.get_credentials(user_id)
  redirect_to authorizer.get_authorization_url(login_hint: user_id, request: request, base_url: "http://localhost:3000")
end

def handle_callback
  credentials = authorizer.get_and_store_credentials_from_code(user_id: "1", code: params[:code], base_url: "http://localhost:3000/oauth2callback")
end
Fellow Stranger
  • 32,129
  • 35
  • 168
  • 232
  • See [the google aaa_oauth guide for ruby](https://developers.google.com/api-client-library/ruby/guide/aaa_oauth), which shows code for a refresh-enabled Sinatra app – max pleaner Aug 06 '16 at 20:35
  • Could you please point to the code that ensures refresh of access_token? – Fellow Stranger Aug 06 '16 at 20:46
  • search for the following text: `session[:refresh_token] = user_credentials.refresh_token` – max pleaner Aug 06 '16 at 20:47
  • Thank you for your help, but that didn't help much unfortunately. I wonder if the API has changed a lot since last year? The page [you refer to](https://developers.google.com/api-client-library/ruby/guide/aaa_oauth) was last updated August 18, 2015. Meanwhile the code that [I've used](https://developers.google.com/google-apps/calendar/quickstart/ruby) has different syntax and was updated June 7, 2016 – Fellow Stranger Aug 06 '16 at 21:12
  • It looks like that Calendar guide is geared toward a one-off login, which doesn't include the refresh stuff. It links to [this page on Oauth 2](https://developers.google.com/api-client-library/ruby/auth/web-app) which is I think where you should look at. – max pleaner Aug 06 '16 at 21:47
  • Alright, thank you! – Fellow Stranger Aug 06 '16 at 22:15
  • 1
    `omniauth-google-oauth2` is great for dealing with the initial user's authentication. I wrote an example on how to refresh the given token for later API requests on that question [with-google-api-client-how-to-create-client](http://stackoverflow.com/questions/42408025/with-google-api-client-how-to-create-client) – Roms Mar 05 '17 at 22:55

0 Answers0