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

我在获取用于实例化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 = '@developer.gserviceaccount.com' ## Path to the Service Account's Private Key file # SERVICE_ACCOUNT_PKCS12_FILE_PATH = '-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("") 

这对我来说就像你使用的是一个较旧的例子。 我想这就是你大约一年前做过的事情。 早在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 => "@developer.gserviceaccount.com", :signing_key => Google::APIClient::KeyUtils.load_from_pkcs12("-privatekey.p12", "notasecret"), :person => "") client.authorization.fetch_access_token! 

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

我使用Java处理过服务帐户+ Drive +文件权限。 为了使用特定用户的权限,我必须允许某些范围。 我唯一可以猜到的问题是你可能错过了代表团的一部分

使用google-api-client的0.9.13版本,我成功地使用了以下对Woodward的回答的轻微改编(注意缺少person参数):

 def service_account_authorization(credentials_file, scope) credentials = JSON.parse(File.open(credentials_file, 'rb').read) authorization = Signet::OAuth2::Client.new( :token_credential_uri => 'https://accounts.google.com/o/oauth2/token', :audience => 'https://accounts.google.com/o/oauth2/token', :scope => scope, :issuer => credentials['client_id'], :signing_key => OpenSSL::PKey::RSA.new(credentials['private_key'], nil), ) authorization.fetch_access_token! authorization end 

此代码段从服务帐户的Google Cloud Console下载文件,并返回可以提供给Google :: Apis :: * Service.authorization的auth对象。

谢谢詹姆斯!