如何在Google API(Ruby)WebmastersV3中使用身份验证令牌(服务帐户访问权限)

问题描述:

我无法将这两部分连接在一起:我能够验证我的服务帐户,并且知道如何形成对我需要从API检索的信息的请求,但是我无法弄清楚如何使该请求通过令牌.

I cannot connect the two pieces together: I am able to authenticate my service account and I know how to form the request for the information I need to retrieve from the API, but I cannot figure out how to make that request authenticated with the token.

这将从我为服务帐户获取的凭证文件中构建一个对象,并成功生成令牌:

This builds an object from the credential file I got for the service account and generates token successfully:

需要"googleauth"

require 'googleauth'

require 'google/apis/webmasters_v3'

website = "https://example.com"

scope = 'https://www.googleapis.com/auth/webmasters'
authorizer = Google::Auth::ServiceAccountCredentials.make_creds(
  json_key_io: File.open('service-account.json'),
 scope: scope)
token = authorizer.fetch_access_token!

最终请求就像

wt_service.query_search_analytics(website, {
  "startDate"=> "2019-12-01",
  "endDate"=> "2019-12-02",
  "dimensions"=> [
    "query"
  ]
})

但是网站站长工具API终结点的对象不接受任何参数:

But the object for the webmaster tools API endpoint does not accept any arguments:

wt_service = Google::Apis::WebmastersV3::WebmastersService.new

但是我需要以某种经过身份验证的方式来构建它,即使用令牌-但是如果我不能添加参数怎么办呢?

But I need to somehow build it in an authenticated way, that is with the token - but how if I cannot add arguments?!

如何使用令牌构建对象?

How do I build the object with the token?

=====

查德威克·伍德的回应解决了这个问题.发生了后续问题,因为Google API使用的变量名不一致,所以我在下面粘贴了完整的工作代码(将服务用户添加到该域的网站站长工具用户列表中后即可正常工作

The response from Chadwick Wood solved it. There was a followup issue because Google API was using inconsistent variable names, so I'm pasting the full working code below (Works after adding the service user to webmaster tools user list for the domain)

require 'googleauth'
require 'google/apis/webmasters_v3'

website = "https://example.com"

scope = 'https://www.googleapis.com/auth/webmasters'
authorizer = Google::Auth::ServiceAccountCredentials.make_creds(json_key_io: File.open('service-account.json'),scope: scope)
token = authorizer.fetch_access_token!
wt_service = Google::Apis::WebmastersV3::WebmastersService.new
wt_service.authorization = authorizer
wt_service.authorization.apply(token)

request_object = {
  start_date: "2019-02-01",
  end_date: "2020-02-28",
  dimensions: ["query"]
}
params = Google::Apis::WebmastersV3::SearchAnalyticsQueryRequest.new(request_object)

res = wt_service.query_search_analytics(website, params)

我认为您只需添加:

wt_service.authorization = authorizer

...在创建服务之后和进行查询之前.所以:

... after you create the service, and before you make the query. So:

authorizer = Google::Auth::ServiceAccountCredentials.make_creds(json_key_io: File.open('service-account.json'), scope: scope)
wt_service = Google::Apis::WebmastersV3::WebmastersService.new
wt_service.authorization = authorizer
wt_service.query_search_analytics ...