无法使用服务帐户

问题描述:

查询谷歌搜索API控制台我需要使用服务帐户检索从谷歌搜索控制台(网站站长工具)的一些数据。无法使用服务帐户

到目前为止,我已经能够检索,我需要追加到请求的URL服务帐户的access_token。问题是,我无法找到一个方法来做到这一点,这是我使用的代码:

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); 
     }); 
    } 

这是由函数调用的网址:

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

相反,它应该是这样的:

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

gapi.client.webmasters.searchanalytics.query不承认'access_token'作为一个有效的密钥因此不追加到URL,这就是为什么我得到一个401 Unauthorized作为响应。

如果我使用'key'代替'access_token'参数被附加到URL,但'key'用于OAuth2认证,这样的服务帐户令牌我传递无效。

有没有人有解决方案或解决方法?

如果您的应用程序请求的私人资料,这个要求必须由谁有权访问这些数据的验证用户的授权。根据Search Console API的the documentation中的规定,您的应用程序必须使用OAuth 2.0来授权请求​​。没有其他授权协议被支持。

如果你的应用是correctly configured,使用谷歌API时,验证的请求看起来就像一个未经身份验证的请求。如the documentation中所述,如果应用程序已收到OAuth 2.0令牌,则JavaScript客户端库会自动在请求中包含该令牌。

您提到您已经检索到access_token,如果正确收到,API客户端会自动为您发送此令牌,您不必自行追加。

一个非常基本的工作流程来验证一旦认证,发送一个请求会看起来像下面的代码。 Search Console API可以使用以下范围:https://www.googleapis.com/auth/webmastershttps://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); 

在这一点上,你retrieveSearchesByQuery功能将需要被修改,因为它并不需要为了通过它查询获得通过争论令牌了。 JavaScript客户端库应该自动将它包含在请求中。

您还可以使用API Explorer检查什么参数是针对特定查询的支持,并检查相关要求。

如果需要使用外部产生的访问令牌,这应该是与服务帐户的情况下,你需要使用gapi.auth.setToken method来套OAuth 2.0 token object自己的应用程序:

gapi.auth.setToken(token_Object); 
+0

谢谢!最后的解决方案是有效的,但使用以下语法:'gapi.auth。setToken({access_token:“YOUR_TOKEN_HERE” });',因为该方法接受一个tokenObject而我有一个字符串。现在我可以正确登录并检索数据 – Signo