1

在过去的几天里,我一直试图在 Ruby 中访问 Google 的 Directory API,但无法使其正常工作。根据文档,可以使用 2lo 对 Directory API 进行授权:

如果您的应用程序有某些不寻常的授权要求,例如在请求数据访问(混合)或域范围授权 (2LO) 的同时登录,那么您目前无法使用 OAuth 2.0 令牌。在这种情况下,您必须改为使用 OAuth 1.0 令牌和 API 密钥。您可以在 Google API 控制台的 API 访问窗格的简单 API 访问部分中找到应用程序的 API 密钥。

我目前有可以使用 2lo 访问 Provisioning API 的工作代码。从文档看来,我可以使用相同的代码访问 Directory API,只需将 API 访问密钥参数添加到请求并启用一些权限即可。但是,它不起作用,我不知道为什么。

这是请求代码:

def self.get_user2(email)
  @client = Google::APIClient.new(:authorization => :two_legged_oauth_1)
  @client.authorization.client_credential_key = GOOGLE_APP_KEY
  @client.authorization.client_credential_secret = GOOGLE_APP_SECRET
  @directory = @client.discovered_api('admin', 'directory_v1')
  result = @client.execute(
    @directory.users.get, 
    'userKey' => email,
    :key => GOOGLE_API_KEY
  )
  JSON.parse(result.body)
end

这让我得到了回应:

{
  "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "authError",
    "message": "Invalid Credentials",
    "locationType": "header",
    "location": "Authorization"
   }
  ],
  "code": 401,
  "message": "Invalid Credentials"
 }
}

我已将所需范围添加到清单文件中,

<Scope id="usersAPI">
  <Url>https://www.googleapis.com/auth/admin.directory.user.readonly</Url>
  <Reason>See all users in your company.</Reason>
</Scope>

并且还在 API 控制台中为我的项目启用了 Admin SDK。

Faraday.default_connection.response :logger这是添加到我的 development.rb 文件后的日志输出:

get https://www.googleapis.com/admin/directory/v1/users/brian@crushing.mygbiz.com?key=AIzaSyAHYBWlC_qiihRtTKTZleZlAw2ts8Q1WO8
User-Agent: "google-api-ruby-client/0.6.4 Mac OS X/10.8.4"
Authorization: "OAuth oauth_consumer_key=\"76548528623.apps.googleusercontent.com\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"1375899810\", oauth_nonce=\"de4d976eed6883a06b3f6084e3dd0db4\", oauth_version=\"1.0\", oauth_signature=\"3D7aqhBeaCYOYyaF8bWpaM9MA8U%3D\""
Cache-Control: "no-store"
Content-Type: "application/x-www-form-urlencoded"
401
www-authenticate: "AuthSub realm=\"https://www.google.com/accounts/AuthSubRequest\""
content-type: "application/json; charset=UTF-8"
date: "Wed, 07 Aug 2013 18:23:30 GMT"
expires: "Wed, 07 Aug 2013 18:23:30 GMT"
cache-control: "private, max-age=0"
x-content-type-options: "nosniff"
x-frame-options: "SAMEORIGIN"
x-xss-protection: "1; mode=block"
server: "GSE"
connection: "close"

在过去一天在互联网上搜索后,我不知道为什么这不起作用。任何人的想法?

4

1 回答 1

1

原来我错过了“xoauth_requestor_id”字段。感谢 sqrrrl 在github上回答我的问题

于 2013-08-08T20:01:25.077 回答