2
votes

I'm a newbie trying to implement the Google Calendar API into a web-based app and after following the instructions that they provide to the t, fetching information only works for about 20 minutes (while the access token is still valid). I understand that you need a refresh token in order to generate a new access token, but running this script from the terminal (which google provided in their documentation) doesn't provide a refresh token.

The code I executed in terminal: google-api oauth-2-login --scope=https://www.googleapis.com/auth/calendar --client- id=CLIENT_ID --client-secret=CLIENT_SECRET

This generated a .yaml file with all of my keys which looks like this:

---
mechanism: oauth_2
scope: SCOPE_HERE
client_id: CLIENT_ID_HERE
client_secret: CLIENT_SECRET_HERE
access_token: ACCESS_TOKEN_HERE
refresh_token: 

And the code that they provided if the access token expires:

oauth_yaml = YAML.load_file('.google-api.yaml')
client = Google::APIClient.new
client.authorization.client_id = oauth_yaml["client_id"]
client.authorization.client_secret = oauth_yaml["client_secret"]
client.authorization.scope = oauth_yaml["scope"]
client.authorization.refresh_token = oauth_yaml["refresh_token"]
client.authorization.access_token = oauth_yaml["access_token"]

if client.authorization.refresh_token && client.authorization.expired?
  client.authorization.fetch_access_token!
end

service = client.discovered_api('calendar', 'v3')

So, according the yaml file, client.authorization.refresh_token is always 'nil', and it never gets a new access token. Also, client.authorization.expired? always returns false, even after the app has stopped working. I've seen some other questions on here pertaining to the same issue, but since I'm generating my tokens via a terminal command, I'm not really sure how to go about getting that refresh token.

1

1 Answers

0
votes

You need to specify that you want offline access to get a refresh token: access_type=offline

See https://developers.google.com/accounts/docs/OAuth2WebServer#offline