0
votes

I'm trying to get offline access to google contacts using the oauth2 ruby Gem (https://github.com/intridea/oauth2). My current code is:

#!/usr/bin/env ruby

require 'oauth2'
require 'yaml'
require 'pp'

auth = YAML.load_file('.auth.yml')
client_id = auth['google']['clientid']
client_secret = auth['google']['secret']
redirect = 'urn:ietf:wg:oauth:2.0:oob'
code = ARGV[0]
token = nil

client = OAuth2::Client.new(client_id, client_secret, site: 'https://accounts.google.com', token_url: '/o/oauth2/token', authorize_url: '/o/oauth2/auth')
if code
  token = client.auth_code.get_token(code, :redirect_uri => redirect)
  auth['google']['token'] = token.to_hash
  open('.auth.yml', 'w'){|f| f.write(auth.to_yaml)}
elsif auth['google']['token']
  token = OAuth2::AccessToken.from_hash(client, auth['google']['token'])
  token.refresh! if token.expired?
  auth['google']['token'] = token.to_hash
  open('.auth.yml', 'w'){|f| f.write(auth.to_yaml)}
else
  puts client.auth_code.authorize_url(scope: 'https://www.google.com/m8/feeds', redirect_uri: redirect, access_type: :offline)
end

pp token.expired? if token

I can use this to get an access token, valid for one hour, and I do see a refresh_token in the response I get when I submit the code I get from the confirmation screen at the generated URL, but the confirmation screen only prompts me for access to my contacts, it does not ask whether I want to give offline access, and the token does indeed expire after an hour. What am I doing wrong?

1

1 Answers

0
votes

Every Access token expires after one hour. when you don't request a offline, the user has to grant access again in order to get a new access token.

When requesting offline access token, as you mentioned, you will receive a refresh token. You will use this refresh token to request a new access token after or before it expires. This is done so the user wont be bothered every hour to grant access.

Here is the documentation about refresh token: https://developers.google.com/identity/protocols/OAuth2WebServer#refresh