2017-04-22 101 views
2

我試圖通過Google API獲取offline access。我必須從Google日曆中提取數據,而不必每次都登錄用戶。如何使用Google API下線訪問

我已經添加到了我的Gemfile:

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

...,並將此向我​​的控制器:

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

在我的行動:

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 

問題是 - 即使我指定「acces s_type「 as 」offline「,I still不會被要求在Google權限列表(我附上下面的屏幕)中提供離線訪問權限。

而這裏的谷歌網頁加載(無離線訪問): Google privileges list with no offline-access request

而這裏的是,當我叫@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

我缺少的東西得到了生成的網址是什麼?

回答

0

嘗試添加代碼。如果你的應用需要一個谷歌API離線訪問,該API客戶端的訪問類型設置爲offline

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

用戶授權之後,以所請求的範圍離線訪問,您可以繼續使用API​​客戶端訪問當用戶離線時代表用戶代表Google API。客戶端對象將根據需要刷新訪問令牌。

還使用Google客戶端庫,這將幫助您刷新訪問令牌(脫機訪問)。

希望這會有所幫助。

+1

感謝@Mr .Rebot - 我已經添加了'access_type'參數,但我仍然沒有在Google的登錄權限頁面上獲得離線訪問提示(它只是要求對日曆進行只讀訪問),並且我在響應中也沒有得到'refresh_token'。 – Qasim

0

您可以嘗試使用這樣的:

client = Signet::OAuth2::Client.new({ 
    client_id: your_client_id, 
    client_secret: your_secret_id, 
    authorization_uri: 'https://accounts.google.com/o/oauth2/auth', 
    scope: Google::Apis::CalendarV3::AUTH_CALENDAR_READONLY, 
    redirect_uri: your_callback_url 
}) 

client.update!(
    additional_parameters: { 
    access_type: 'offline', 
    prompt: 'consent' 
    } 
) 

redirect_to client.authorization_uri.to_s 

請注意,我用的是google-api-client寶石的較新版本,配置是這樣的:

gem 'google-api-client', '~> 0.11', require: 'google/apis/calendar_v3' 

這樣,谷歌會問你獲取與Calendar API交互的權限並正確設置access_type參數以授予您對相同API的脫機訪問權限。

這種方法將在您每次調用代碼時提示用戶進行授權。如果你想避免這種情況,你要這樣改:

client.update!(
    additional_parameters: { 
    access_type: 'offline' 
    } 
) 

如果您已經授權您的應用程序,而不access_type: 'offline'參數谷歌將授予你一個身份驗證令牌不離線許可證。要重置此情況,只需進入your Google profile permissions並撤銷之前的應用程序授權即可。然後再試一次。

(注:signet寶石的googleauth的依賴,而這又是google-api-client的依賴,讓你免費獲得此代碼,而不需要更多的寶石添加到Gemfile

相關問題