Node.js - Can't access my account from the Google Drive API

天涯浪子 提交于 2020-01-16 19:33:11

问题


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.

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"
  }]
}

回答1:


First off, if you get lost, this quick start from Google is probably better than the tutorial.

Secondly, to get access to your drive you must request the appropriate scope within your app, and you must authorize the app's requested permissions (scopes) by visiting a URL that will be provided during the authorization process. Here is a guide to scopes.




回答2:


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

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] Do I need G Suite account to make requests impersonating an user with a service account?

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

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



来源:https://stackoverflow.com/questions/59471961/node-js-cant-access-my-account-from-the-google-drive-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!