【问题标题】:How can I authorize with OAuth 2.0 for google's predictive API in Ruby?如何使用 OAuth 2.0 授权 Ruby 中的谷歌预测 API?
【发布时间】:2013-01-18 02:49:47
【问题描述】:

我试图简单地向谷歌的托管模型 sample.sentiment 发送一个请求。我无法弄清楚如何通过谷歌使用 Oauth 2.0 进行授权,而且我得到了无数个小时。如果你能提供给我这个代码会很有帮助。这就是我的工作。

client = Google::APIClient.new({:application_name => "CCE",:application_version => "1.0"} )
plus = client.discovered_api('prediction')

# Initialize OAuth 2.0 client    
client.authorization.client_id = 'my client id'
client.authorization.client_secret = 'my client secret'
client.authorization.redirect_uri = 'my callback url'

client.authorization.scope = 'https://www.googleapis.com/auth/prediction'

# Request authorization
redirect_uri = client.authorization.authorization_uri

# Wait for authorization code then exchange for token
client.authorization.code = '....'
client.authorization.fetch_access_token!

# Make an API call
 result = client.execute(
   :api_method => plus.activities.list,
   :parameters => {'hostedModelName' => 'sample.sentiment', 'userId' => ''})

`

【问题讨论】:

    标签: ruby api google-api


    【解决方案1】:

    好吧,网络上的示例可能有点令人困惑,但是如果您想利用服务器-服务器通信 - 这意味着不涉及最终用户和浏览器,那么以下代码应该适合您:

    先决条件:

    • 您应该在您的 Google API 控制台中生成一个“服务帐户”密钥。它会提示您下载私钥,您应该将其存储在磁盘上的某个位置,例如 client.p12(或使用原始名称,但为了清楚起见,我将使用较短的名称)。
    client = Google::APIClient.new(
      :application_name => "CCE",
      :application_version => "1.0"
    )
    prediction = client.discovered_api('prediction', 'v1.5')
    
    key = Google::APIClient::KeyUtils.load_from_pkcs12('client.p12', 'notasecret')
    
    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/prediction',
      :issuer => '..put here your developer email address from Google API Console..',
      :signing_key => key,
    )
    client.authorization.fetch_access_token!
    
    # Now you can make the API calls
    result = client.execute(...
    

    值得注意的是client.discovered_api 调用似乎需要版本号。否则它可能会抛出异常'NotFound'。

    密码实际上是字符串'notasecret'!

    另一件事:在 API 调用中确保调用正确的方法 - 对于托管模型,我相信您可以调用的唯一方法是 :api_method => prediction.hostedmodels.predict 或类似的方法。我还没有使用托管模型。 (see the API docs for details)

    client.execute 调用返回的result 可能感兴趣的字段是:

    result.status
    result.data['error']['errors'].map{|e| e['message']} # if they exist
    JSON.parse(result.body)
    

    如果您检查它们,它们可能会极大地帮助您调试任何问题。

    【讨论】:

    • 这对我入门很有帮助。只是为了向其他人澄清-这里涉及两种帐户; “服务”帐户使用私钥进行身份验证,“Web”帐户使用回调挂钩进行身份验证。 OP 使用回调提供身份验证,此答案使用带有私钥的服务帐户。从理论上讲,应该可以使用 Web 帐户和回调来进行操作。
    猜你喜欢
    • 2012-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-14
    • 1970-01-01
    • 2012-11-12
    • 2017-07-31
    相关资源
    最近更新 更多