How to use auth token in Google API (Ruby) WebmastersV3 (service account access)

拈花ヽ惹草 提交于 2020-06-29 03:59:30

问题


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:

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!

The final request is like

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

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?

=====

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)

回答1:


I think you just have to add:

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 ...


来源:https://stackoverflow.com/questions/59486977/how-to-use-auth-token-in-google-api-ruby-webmastersv3-service-account-access

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!