Unable to query Google Search Console API using a Service Account

依然范特西╮ 提交于 2020-08-24 03:48:03

问题


I need to retrieve some data from Google Search Console (Webmaster Tools) using a service account.

So far I've been able to retrieve an access_token for the service account which I need to append to the url of the request. The problem is that I can't find a way to do so, this is the code i'm using:

function retrieveSearchesByQuery(token)
    {
        gapi.client.webmasters.searchanalytics.query(
        {
            'access_token': token,
            'siteUrl': 'http://www.WEBSITE.com',
            'fields': 'responseAggregationType,rows',
            'resource': {
                'startDate': formatDate(cSDate),
                'endDate': formatDate(cEDate),
                'dimensions': [
                    'date'
                ]
            }
        })
        .then(function(response) {
            console.log(response);
        })
        .then(null, function(err) {
            console.log(err);
        });
    }

This is the url called by the function:

https://content.googleapis.com/webmasters/v3/sites/http%3A%2F%2Fwww.WEBSITE.com/searchAnalytics/query?fields=responseAggregationType%2Crows&alt=json"

Instead it should be something like this:

https://content.googleapis.com/webmasters/v3/sites/http%3A%2F%2Fwww.WEBSITE.com/searchAnalytics/query?fields=responseAggregationType%2Crows&alt=json&access_token=XXX"

The gapi.client.webmasters.searchanalytics.query doesn't recognize 'access_token' as a valid key thus it doesn't append it to the url and that's why I get a 401 Unauthorized as response.

If I use 'key' instead of 'access_token' the parameter gets appended to the url but 'key' is used for OAuth2 authentication so the service account token I pass is not valid.

Does anyone have a solution or a workaround for this?


回答1:


If your application requests private data, the request must be authorized by an authenticated user who has access to that data. As specified in the documentation of the Search Console API, your application must use OAuth 2.0 to authorize requests. No other authorization protocols are supported.

If you application is correctly configured, when using the Google API, an authenticated request looks exactly like an unauthenticated request. As stated in the documentation, if the application has received an OAuth 2.0 token, the JavaScript client library includes it in the request automatically.

You're mentioning that you have retrieved an access_token, if correctly received, the API client will automatically send this token for you, you don't have to append it yourself.

A very basic workflow to authenticate and once authenticated, send a request would looks like the following code. The Search Console API can use the following scopes: https://www.googleapis.com/auth/webmasters and https://www.googleapis.com/auth/webmasters.readonly.

var clientId = 'YOUR CLIENT ID';
var apiKey = 'YOUR API KEY';
var scopes = 'https://www.googleapis.com/auth/webmasters';

function auth() {
  // Set the API key.
  gapi.client.setApiKey(apiKey);

  // Start the auth process using our client ID & the required scopes.
  gapi.auth2.init({
      client_id: clientId,
      scope: scopes
  })
  .then(function () {
    // We're authenticated, let's go...
    // Load the webmasters API, then query the API
    gapi.client.load('webmasters', 'v3')
      .then(retrieveSearchesByQuery);
  });
}

// Load the API client and auth library
gapi.load('client:auth2', auth);

At this point, your retrieveSearchesByQuery function will need to be modified since it doesn't need to get a token by argument anymore in order to pass it in the query. The JavaScript client library should include it in the request automatically.

You can also use the API Explorer to check what parameters are supported for a specific query and check the associated request.

If you need to use an externally generated access token, which should be the case with a Service Account, you need to use the gapi.auth.setToken method to sets the OAuth 2.0 token object yourself for the application:

gapi.auth.setToken(token_Object);


来源:https://stackoverflow.com/questions/38653502/unable-to-query-google-search-console-api-using-a-service-account

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