【问题标题】:Access Google Drive files through API from service account从服务帐户通过 API 访问 Google Drive 文件
【发布时间】:2015-09-15 05:37:38
【问题描述】:

我正在将 Ruby on Rails 与 Google Drive API (https://github.com/gimite/google-drive-ruby) 结合使用,并尝试在网页中显示我的 Google 帐户上的电子表格中的数据。

这是我用来授权应用程序使用我的 Google Drive 帐户的代码。我在 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) 授权应用程序时如何启动会话的文档,并且我正在使用开发人员控制台中生成的凭据。 . 我想弄清楚的是如何在使用预先生成的服务帐户凭据登录时启动会话。

【问题讨论】:

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


    【解决方案1】:

    您应该能够在 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

    【讨论】:

    • 我应该在哪里添加那段代码?我已经有了 client_secret.json,但我现在知道在哪里添加代码以与我的解决方案集成。它是控制器吗?一个模型?那是什么,我可以在哪里使用我的模型?我不知道,我也找不到任何帮手
    猜你喜欢
    • 2020-07-14
    • 2017-08-31
    • 2021-09-05
    • 2020-10-25
    • 2017-11-17
    • 2017-06-29
    • 1970-01-01
    • 2019-12-12
    • 2020-01-21
    相关资源
    最近更新 更多