2013-08-27 53 views
3

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

奇怪的是,如果我省略了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>") 

回答

8

这对我来说就像你使用的是一个较老的例子。我想这就是大约一年前你曾经这么做的原因。早在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! 

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

+0

有趣,而且看起来更清洁。我终于把它和我的代码一起工作了。我在某个阶段肯定有一个错字,但我发誓我会三重检查一切。 – JRQ

+0

奇怪,因为在[Google文档在这里](https://developers.google.com/drive/web/delegation)显示的ruby示例看起来就像OP的。你有Signet方法的文档吗? – mmcrae

+0

太棒了,这个答案在这里提示了一个方便的拉动请求! https://github.com/northworld/google_calendar/pull/95 –

2

我已经使用Java的服务帐户+驱动器+文件权限。为了对特定用户使用权限,我必须允许某个范围。关于你的问题,我唯一可以猜到的是你可能错过了the Delegation part

+0

谢谢,但我已经包含了这个上演。我最终回头几次,重新从头开始整个过程​​。在第三次开始工作时,所以我必须假设我在某个阶段肯定粘贴了错误的东西。 – JRQ

2

使用google-api-client版本0.9.13,我成功地使用了Woodward的答案的下面的一些小改动(注意人的缺席参数):

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 

这个片段需要一个文件,因为它是从谷歌云端控制台下载的服务帐户,并返回一个可以被馈送到谷歌::蜜蜂:: * Service.authorization一个auth对象。

谢谢詹姆斯!

相关问题