问题
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