Get a token, save it, upgrade if expired using oauth2 gem in ruby

I am working on a script to get google contacts using google contacts api gem . I can successfully access the token 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 this, because it is tiring. every time I run the script, the user provides access instructions. And also I need to manually copy the marker pack from the browser to the terminal.

Question:

How can I save the extracted token, and when it has expired, how can I update it?

+5
source share
3 answers

It looks like you are using the oauth2 library to get the access token. The AccessToken class has the to_hash() and from_hash() methods, which you can use to serialize and deserialize the token after it is received, as well as the refresh() method to update the access token after its expiration. If this is a command line script, you can use a hidden file in the user's home directory to store the serialized token.

+6
source

During the first authentication, you receive an authorization token and an update token.

Save refresh_token (in a session, if it is a web application or any other "volatile" save scheme, or in the latter case in the database).

Using refresh_token, ask for a new token, as described in the Google OAuth2 WebServer Documentation .

If this is not a web server application, you might consider using other OAuth2 authentication flows .

+3
source

To get the update token, you need to change the URL .

in OAuth2:

url = client.auth_code.authorize_url(scope: OAUTH_SCOPE, access_type: "offline", redirect_uri: REDIRECT_URI)

It will then be available, as Eric Coleda mentions.

+1
source

Source: https://habr.com/ru/post/1205351/


All Articles