使用Ruby中的Google Apps API和服务帐户时出现问题

JRQ*_*JRQ 3 ruby google-api google-drive-api google-api-ruby-client

我在获取用于实例化Drive Service帐户的示例代码时遇到了一些麻烦.我已按照指示在API控制台中设置服务帐户,并包含" https://www.googleapis.com/auth/drive " 的范围,但运行此帐户会生成以下错误:"授权失败.服务器消息:(Signet :: AuthorizationError)".

奇怪的是,如果我省略user_email地址,它不会产生错误.

我的目标是能够对组织的驱动器上存储的所有文件进行审核,我的理解是使用服务帐户可以获得存储的所有文件的列表.

我是否错过了服务器端的一些特殊设置?

require 'google/api_client'

## Email of the Service Account #
SERVICE_ACCOUNT_EMAIL = '<service account email>@developer.gserviceaccount.com'

## Path to the Service Account's Private Key file #
SERVICE_ACCOUNT_PKCS12_FILE_PATH = '<private key file>-privatekey.p12'

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)
    return client
end

client = build_client("<users email address>")
Run Code Online (Sandbox Code Playgroud)

Jam*_*ard 9

这对我来说就像你使用的是一个较旧的例子.我想这就是你大约一年前做过的事情.早在2012年底,不推荐使用设置应用程序的方法,因为Signet已更新以处理OAuth2设置的所有方面.

这是我通常用来创建服务帐户的代码.您可以调整它以适合您的方法.

client.authorization = Signet::OAuth2::Client.new(
 :token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
 :audience => 'https://accounts.google.com/o/oauth2/token',
 :scope => "https://www.googleapis.com/auth/drive",
 :issuer => "<service account email>@developer.gserviceaccount.com",
 :signing_key => Google::APIClient::KeyUtils.load_from_pkcs12("<private key file>-privatekey.p12", "notasecret"),
 :person => "<users email address>")
client.authorization.fetch_access_token!
Run Code Online (Sandbox Code Playgroud)

如果您仍有问题,请告诉我,我会看看我是否可以提供帮助.