【发布时间】:2020-06-09 10:31:46
【问题描述】:
我想知道是否可以使用服务帐户从任何 google API 请求数据但使用此库:https://github.com/google/google-api-javascript-client
我设法从谷歌云控制台了解如何使用带有 OAuth2.0 凭据的库。 但我真正需要的是使用服务帐号来获取这些数据。
这是我用来从 OAuth2.0 凭据中获取数据的代码:
initClient() {
return gapi.client.init({
apiKey: this.GSC_API_KEY, // already defined in the application
client_id:
"xxxxxxxxxxxxxxxxx.apps.googleusercontent.com",
scope:
"https://www.googleapis.com/auth/webmasters https://www.googleapis.com/auth/webmasters.readonly",
discoveryDocs: [
"https://www.googleapis.com/discovery/v1/apis/webmasters/v3/rest"
]
});
},
gapiList() {
this.initClient()
.then(() => {
// Executes an API request, and returns a Promise.
// The method name `webmasters.sites.list` comes from the API webmasters.
return gapi.client.webmasters.sites.list();
})
.then(
response => {
console.log(response.body);
},
err => {
console.error(err.details);
}
);
},
以下是请求 API 的代码:
gapi.load("client", this.gapiList);
它确实返回了很好的数据。
但我的最终目的需要我使用服务帐户。
initClient 函数确实需要一个 client_id 才能正确加载。如果我提供服务帐户的 client_id,它确实会返回一个错误。
"Not a valid origin for the client: http://localhost:8080/ has not been whitelisted for client ID xxxxxxxxxxxxx. Please go to https://console.developers.google.com/ and whitelist this origin for your project's client ID.
错误消息告诉我将 localhost(我目前正在工作的地方)列入白名单,但我没有找到如何将服务帐户的 localhost 列入白名单。
希望我提供了足够的信息。
感谢您的回复和帮助。
【问题讨论】:
标签: javascript api google-api google-oauth service-accounts