【发布时间】:2021-04-24 08:43:55
【问题描述】:
我正在构建一个 Node.js CLI,它执行在函数中预定义的 Google Drive API 和 Docs API 调用。
但是因为每个 API 调用都必须经过授权,所以我创建了一个单独的文件和函数来读取凭据,并且应该返回授权的 oAuth2Client 对象,以便在需要作为参数传递的任何函数中导出和重用。
这个想法是readCredentials() 函数调用将调用authorize() 函数,如果存在token.json,它应该返回oAuth2Client 对象。否则它将提示用户使用getAccessToken() 函数进行身份验证。
整个逻辑实际上只是从quickstart example in the Google Drive API docs 略微修改,但旨在可在应用程序的任何功能中重用,而不仅仅是在当前文件中。
但是由于某种原因,当我尝试调用凭据并将其存储在变量中时,我在控制台中返回了GaxiosError: Login Required,然后使用它们在我的index.js 中授权API 调用。
有人知道出了什么问题吗?
authorize.js
const fs = require("fs");
const readline = require("readline");
const { google } = require("googleapis");
const SCOPES = ["https://www.googleapis.com/auth/drive.file"];
const TOKEN_PATH = "token.json";
const readCredentials = () => {
fs.readFile("credentials.json", (err, content) => {
if (err) return console.log("Error loading client secret file:", err);
authorize(JSON.parse(content));
});
};
const authorize = (credentials) => {
const { client_secret, client_id, redirect_uris } = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(
client_id,
client_secret,
redirect_uris[0]
);
fs.readFile(TOKEN_PATH, (err, token) => {
if (err) return getAccessToken(oAuth2Client);
oAuth2Client.setCredentials(JSON.parse(token));
});
return oAuth2Client;
};
const getAccessToken = (oAuth2Client) => {
const authUrl = oAuth2Client.generateAuthUrl({
access_type: "offline",
scope: SCOPES,
});
console.log("Authorize this app by visiting this url:", authUrl);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question("Enter the code from that page here: ", (code) => {
rl.close();
oAuth2Client.getToken(code, (err, token) => {
if (err) return console.error("Error retrieving access token", err);
oAuth2Client.setCredentials(token);
fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
if (err) return console.error(err);
console.log("Token stored to", TOKEN_PATH);
});
return oAuth2Client;
});
});
};
module.exports = { readCredentials };
index.js
const authorize = require("./authorize");
const drive = require("./drive");
...
let credentials = authorize.readCredentials();
drive.createFolder(credentials);
...
【问题讨论】:
-
不是范围的问题吧?您没有混合对需要不同范围的不同端点的调用,然后是您在此处显示的那个。
标签: javascript node.js google-api google-drive-api google-oauth