3

How to connect offline with Google APIs

 3 years ago
source link: https://www.codesd.com/item/how-to-connect-offline-with-google-apis.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How to connect offline with Google APIs

advertisements

I'm trying to get offline access with Google APIs. I have to pull data from Google Calendar without having the user sign-in everytime.

I've added this to my Gemfile:

gem 'google-api-client', '~> 0.9'

... And added this to my controller:

require 'google/api_client/client_secrets'
class Api::V1::CalendarAccountsController < Api::V1::BaseController
...

And in my action:

client_secrets = Google::APIClient::ClientSecrets.load(
  File.join(
    Rails.root,
    'config',
    'client_secrets.json')
  )

@auth_client = client_secrets.to_authorization

@auth_client.update!(
    :scope => 'https://www.googleapis.com/auth/calendar.readonly',
    :redirect_uri => '/{callback URL}',

    :additional_parameters => {
      "access_type" => "offline",
      "include_granted_scopes" => "true"
    }
)
redirect_to @auth_client.authorization_uri.to_s

The problem is -- even though I'm specifying "access_type" as "offline", I still don't get asked for offline-access privileges in the Google privileges list (I'm attaching a screenie below).

And here's the page Google loads (no offline-access):

And here's the URL that got generated when I called @auth_client.authorization_uri.to_s

https://accounts.google.com/o/oauth2/auth?access_type=offline&client_id=[ID]&redirect_uri=[callback]&response_type=code&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar.readonly&from_login=1&as=-23788065e9c098d9&pli=1&authuser=0

Am I missing something?


Try adding this code. If your application needs offline access to a Google API, set the API client's access type to offline:

auth_client.update!(
  :additional_parameters => {"access_type" => "offline"}
)

After a user grants offline access to the requested scopes, you can continue to use the API client to access Google APIs on the user's behalf when the user is offline. The client object will refresh the access token as needed.

Also use the Google client library, this will help you with refreshing an access token (offline access).

Hope this helps.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK