使用 devise+omniauth access_token 从 Google 表格中提取

using devise+omniauth access_token to pull from Google Sheets

我想从登录用户的 Google 表格电子表格中提取数据以进行某些处理。我在 Google Console 中设置了一个应用程序:

我还连接了 devise/oauth 以便它可以成功登录。但是,每当我尝试使用 from_omniauth 方法中收到的 access_token 时,我都会得到:

dailyLimitExceededUnreg: Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.

我做错了什么?

我的代码(使用google-api-client)如下:

# frozen_string_literal: true
require 'google/apis/drive_v2'

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable,
         :omniauthable, omniauth_providers: [:google_oauth2]
  has_many :datasets, inverse_of: :user

  # Omniauth support
  def self.from_omniauth(access_token)
    #session = GoogleDrive::Session.new( access_token )
    drive = Google::Apis::DriveV2::DriveService.new
    files = drive.list_files(
      fields: "nextPageToken, files(id, name)",
      q: "mimeType = 'application/vnd.google-apps.spreadsheet' AND trashed != true",
    )


    data = access_token.info
    user = User.where(email: data['email']).first

    unless user
      user = User.create(
        email: data['email'],
        password: Devise.friendly_token[0, 20]
      )
    end
    user
  end
end

郑重声明,我也尝试使用 google-drive gem 并得到了相同的响应。

该错误消息表示您对云端硬盘的请求缺少 Authorization: http header。这通常看起来像 Authorization: bearer xxxxxxxxx,其中 xxxxx 是访问令牌。

我在你的代码中看不到你将访问令牌设置到 drive object 的任何地方(但注意我不知道 Ruby)。

虽然@pinyyid 本身没有完整的答案,但它确认我没有正确传递凭据(我之前尝试过,但没有正确)。最终,需要进行以下更改才能使用 google-drive gem:

config.omniauth :google_oauth2, '<CLIENT_ID>', '<SECRET_KEY', scope: 'https://www.googleapis.com/auth/drive,https://spreadsheets.google.com/feeds/,https://www.googleapis.com/auth/plus.login,https://www.googleapis.com/auth/userinfo.email,https://www.googleapis.com/auth/userinfo.profile'

这里的关键是将我需要的范围添加到设计请求中。

然后,在我的用户对象中,我使用了以下内容:

def self.from_omniauth(access_token)
   session = GoogleDrive::Session.from_access_token(access_token[:credentials][:token])
   x = session.spreadsheet_by_title '<a spreadsheet title>' #or any call, really

希望对大家有所帮助!