通过API从服务帐户访问Google云端硬盘文件

时间:2015-09-15 05:37:38

标签: ruby-on-rails ruby google-drive-api

我正在使用带有Google云端硬盘API的Ruby on Rails(https://github.com/gimite/google-drive-ruby),我正试图在网页上的Google帐户中显示电子表格中的数据。

这是我用来授权应用程序使用我的Google云端硬盘帐户的代码。我已在Google Developers控制台中为服务帐户生成凭据。

def build_client(credentials)
  client = Google::APIClient.new
  client.authorization = credentials
  client = client.discovered_api('drive', 'v2')
  client
end

现在访问我需要开始新会话的文件,但是只有在通过OAuth(https://github.com/gimite/google-drive-ruby#how-to-use)授权应用程序时如何启动会话的文档,我使用的是开发人员控制台中生成的凭据...我想弄清楚的是如何在使用预先生成的服务帐户凭据登录时启动会话。

1 个答案:

答案 0 :(得分:0)

您应该能够在console.google.com中从项目中获取凭据。从那里,我们必须更新google_drive.rb中的代码,以便作为服务帐户进行身份验证。代码应该是这样的:

require 'google/api_client'

## Email of the Service Account #
SERVICE_ACCOUNT_EMAIL = '<some-id>@developer.gserviceaccount.com'

## Path to the Service Account's Private Key file #
SERVICE_ACCOUNT_PKCS12_FILE_PATH = '/path/to/<public_key_fingerprint>-privatekey.p12'

##
# Build a Drive client instance authorized with the service account
# that acts on behalf of the given user.
#
# @param [String] user_email
#   The email of the user.
# @return [Google::APIClient]
#   Client instance
def build_client(user_email)
    key = Google::APIClient::PKCS12.load_key(SERVICE_ACCOUNT_PKCS12_FILE_PATH, 'notasecret')
    asserter = Google::APIClient::JWTAsserter.new(SERVICE_ACCOUNT_EMAIL,
        'https://www.googleapis.com/auth/drive', key)
    client = Google::APIClient.new
    client.authorization = asserter.authorize(user_email)
    client
end

您可以找到更多信息here