如果您的应用程序请求私有数据,则该请求必须由有权访问该数据的经过身份验证的用户授权。如指定文档 https://developers.google.com/webmaster-tools/v3/how-tos/authorizingSearch Console API 的一部分,您的应用程序必须使用 OAuth 2.0 来授权请求。不支持其他授权协议。
如果您的申请是正确配置 https://developers.google.com/api-client-library/javascript/features/authentication,当使用 Google API 时,经过身份验证的请求看起来与未经身份验证的请求完全相同。如中所述文档 https://developers.google.com/api-client-library/javascript/features/authentication,如果应用程序收到 OAuth 2.0 令牌,JavaScript 客户端库会自动将其包含在请求中。
您提到您已经检索到access_token
,如果正确接收,API客户端会自动为您发送此令牌,您不必自己附加它。
一个非常基本的身份验证工作流程,一旦通过身份验证,发送请求将类似于以下代码。 Search Console API 可以使用以下范围: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);
此时,您的retrieveSearchesByQuery
函数将需要修改,因为它不再需要通过参数获取令牌才能在查询中传递它。 JavaScript 客户端库应自动将其包含在请求中。
您还可以使用API浏览器 https://developers.google.com/apis-explorer/#p/webmasters/v3/webmasters.searchanalytics.query检查特定查询支持哪些参数并检查关联的请求。
如果您需要使用外部生成的访问令牌(服务帐户应该是这种情况),则需要使用gapi.auth.setToken method https://developers.google.com/api-client-library/javascript/reference/referencedocs#gapiauthsetToken设置OAuth 2.0 令牌对象 https://developers.google.com/api-client-library/javascript/reference/referencedocs#oauth-20-token-object自己申请:
gapi.auth.setToken(token_Object);