簡體   English   中英

如何授權 google-api-ruby-client?

[英]How to authorize the google-api-ruby-client?

我正在努力按照此處的基本用法示例使 google-api-ruby-client gem 正常工作:基本用法

require 'google/apis/drive_v2'

Drive = Google::Apis::DriveV2 # Alias the module
drive = Drive::DriveService.new
drive.authorization = ... # See Googleauth or Signet libraries

# Search for files in Drive (first page only)
files = drive.list_files(q: "title contains 'finances'")
files.items.each do |file|
  puts file.title
end

我被卡住的地方是drive.authorization 我已經通過 gem omniauth-google-oauth2 為用戶提供了一個授權令牌。 如何在 google-api-ruby-client 中使用該令牌?

我也被卡住了。 IMO Google 應該在他們的文檔中詳細說明,特別是因為我們所要做的只是添加一個請求標頭......

無論如何,這是一個例子。

#
# Note I don't think we always have to define a class with such a conflict-prone name. 
# An anonymous class defined before every single API call should be also fine.
#
module Google
  class AccessToken
    attr_reader :token
    def initialize(token)
      @token = token
    end

    def apply!(headers)
      headers['Authorization'] = "Bearer #{@token}"
    end
  end
end
Drive = Google::Apis::DriveV2
drive = Drive::DriveService.new
drive.authorization = Google::AccessToken.new your_token

參考: https : //github.com/google/google-api-ruby-client/issues/296

與其他答案類似,我采用了這種方法,其中使用了存儲身份驗證和刷新令牌的模型,從該邏輯中抽象出 API 交互。

# Manages access tokens for users when using Google APIs
#
# Usage:
# require 'google/apis/gmail_v1'
# Gmail = Google::Apis::GmailV1 # Alias the module
# service = Gmail::GmailService.new
# service.authorization = GoogleOauth2Authorization.new user
# service.list_user_messages(user.email)
#
# See also:
# https://github.com/google/google-api-ruby-client/issues/296
class GoogleOauth2Authorization
  attr_reader :user

  def initialize(user)
    @user = user
  end

  def apply!(headers)
    headers['Authorization'] = "Bearer #{token}"
  end

  def token
    refresh! if user.provider_token_expires_at.past?
    user.provider_access_token
  end

  private

  def refresh!
    new_token = oauth_access_token(
      user.provider_access_token,
      user.provider_refresh_token
    ).refresh!
    if new_token.present?
      user.update(
        provider_access_token: new_token.token,
        provider_token_expires_at: Time.zone.at(new_token.expires_at),
        provider_refresh_token: new_token.refresh_token
      )
    end
    user
  end

  def oauth_access_token(access_token, refresh_token)
    OAuth2::AccessToken.new(
      oauth_strategy.client,
      access_token,
      refresh_token: refresh_token
    )
  end

  def oauth_strategy
    OmniAuth::Strategies::GoogleOauth2.new(
      nil,
      Rails.application.credentials.oauth[:google_id],
      Rails.application.credentials.oauth[:google_secret]
    )
  end
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM