Reputation: 6180
I am working on script to get google contacts using google contacts api gem. I am able to access the token successfully using this code:
require 'rubygems'
require 'launchy'
require 'oauth2'
require 'googlecontacts'
require 'google_contacts_api'
# Get your credentials from the console
CLIENT_ID = 'your Id'
CLIENT_SECRET = 'your Secret'
OAUTH_SCOPE = 'https://www.google.com/m8/feeds'
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
client = OAuth2::Client.new(CLIENT_ID, CLIENT_SECRET,site: 'https://accounts.google.com',token_url: '/o/oauth2/token', authorize_url: '/o/oauth2/auth')
url = client.auth_code.authorize_url(scope: OAUTH_SCOPE, redirect_uri: REDIRECT_URI)
Launchy.open(url)
$stdout.write "Enter authorization code: "
code = gets.chomp
token = client.auth_code.get_token(code, :redirect_uri => REDIRECT_URI)
PROBLEM:
I know that this is not the best way to do it, because it is tiring. every time I run the script the user has give access instructions. And also I have to manually copy paste the token from the browser to the terminal.
QUESTION:
How can be able to store the retrieved token, and when it expired how can I refresh it?
Upvotes: 5
Views: 10579
Reputation: 191
In order to receive a refresh token, you need to alter the url.
in OAuth2:
url = client.auth_code.authorize_url(scope: OAUTH_SCOPE, access_type: "offline", redirect_uri: REDIRECT_URI)
Then it will be available like Erik Koleda mentions.
Upvotes: 1
Reputation: 12673
It looks like you're using the oauth2 library to get the access token. The AccessToken class has to_hash()
and from_hash()
methods, which you can use to serialize and deserialize the token once you've gotten it, as well as a refresh()
method to refresh the access token once it's expired. If this is a command line script you can use a hidden file in the user's home directory to store the serialized token.
Upvotes: 8
Reputation: 3542
During the first authentication, you got an authorization token and a refresh token.
Store the refresh_token (in session if it's a web app, or any other "volatile" persistence scheme, or in last case in database).
Using the refresh_token, ask for a new token like described in Google OAuth2 WebServer documentation.
If this is not a webserver application, maybe you should consider use other OAuth2 authentication flows.
Upvotes: 3