[英]Can I set my Node.js Backend to access my Google Drive to list/download/upload?
[英]Node.js - Can't access my account from the Google Drive API
我需要以编程方式修改我的 Google 云端硬盘,以便能够创建文件夹并将一堆文件上传到它们,然后在需要时删除该根文件夹并重做整个过程。
我创建了一个具有服务帐户的项目,然后下载了 JSON 并将其存储在我的计算机上。
接下来,我跟着这个教程。
我最终得到了这个代码:
const auth = await google.auth.getClient({
credentials: require(pathToServiceAccountJSON),
scopes: "https://www.googleapis.com/auth/drive"
});
const drive = await google.drive({ version: "v3", auth });
drive.files
.create({
resource: {
name: filename,
mimeType: "application/vnd.google-apps.folder",
parents: [parentId]
}
})
.then(result => console.log("SUCCESS:", result))
.catch(console.error);
但是,执行它会导致抛出以下错误:
{
...
errors: [{
domain: "global",
reason: "forbidden",
message: "Forbidden"
}]
}
为了能够使用服务帐户模拟用户(如您自己或域中的任何其他人),您需要在域范围内启用它,为此您需要拥有一个 G Suite 帐户 [1]。 如果是这种情况,从库示例 [2] 中,您需要在构造 JWT 对象时将要模拟的用户添加为第 5 个参数:
const {JWT} = require('google-auth-library');
const keys = require('./jwt.keys.json');
async function main() {
const client = new JWT(
keys.client_email,
null,
keys.private_key,
['https://www.googleapis.com/auth/cloud-platform'],
'userToImpersonate@example.com'
);
const url = `https://dns.googleapis.com/dns/v1/projects/${keys.project_id}`;
const res = await client.request({url});
console.log(res.data);
}
如果您没有 G Suite 帐户,您只需按照快速入门 [3] 步骤获取驱动器服务,然后使用它提出创建请求。
[1] 是否需要 G Suite 帐户才能使用服务帐户模拟用户发出请求?
[2] https://github.com/googleapis/google-auth-library-nodejs#json-web-tokens
[3] https://developers.google.com/drive/api/v3/quickstart/nodejs
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.