Node.js-无法通过Google Drive API访问我的帐户 [英] Node.js - Can't access my account from the Google Drive API

查看:63
本文介绍了Node.js-无法通过Google Drive API访问我的帐户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就创建文件夹并将其上传到其中的能力而言,我需要以编程方式修改我的Google云端硬盘,然后在需要时删除该根文件夹并重做整个过程.

I need to programmatically modify my Google Drive, in terms of the ability to create folders and uploading to them a bunch of files, and then, when needed - remove that root folder and redo the whole process.

我创建了一个具有服务帐户的项目,然后下载了JSON,并将其存储在我的计算机上.
接下来,我遵循了本教程

I've created a project that has a service account, then downloaded the JSON and it's stored on my computer.
Next, I followed this tutorial.

我最终得到了这段代码:

I ended up with this code:

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

但是,执行它会引发以下错误:

However, executing it causing the following error to be thrown:

{
  ...
  errors: [{
    domain: "global",
    reason: "forbidden",
    message: "Forbidden"
  }]
}

推荐答案

要能够使用服务帐户模拟用户(例如您本人或域中的其他任何人),您需要在域范围内启用该服务,为此,您需要有一个G Suite帐户[1].在这种情况下,从库示例[2]中,您需要在构造JWT对象时添加要模拟的用户作为第五个参数:

To be able to impersonate a user(like yourself or any other in a domain) with a service account you need to have it with domain-wide delegation on, to do this you need to have a G suite account [1]. If this is the case, from the library example [2], you need to add the user you want to impersonate as the 5th parameter when constructing the JWT object:

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]步骤获得驱动器服务,然后使用它进行创建请求.

If you don't have G Suite account, you could simply follow the quickstart [3] steps to get drive service and then make your create request with it.

[1] [2] https://github.com/googleapis/google-auth-library-nodejs#json-web-tokens

[3] https://developers.google.com/drive/api/v3/quickstart/nodejs

这篇关于Node.js-无法通过Google Drive API访问我的帐户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆