Google OAuth 使用全域委派和服务帐户

Google OAuth using domain wide delegation and service account

我正在尝试通过使用服务帐户使用全域委派来进行 google 驱动 API 调用。 我可以进行身份​​验证,但不能进行驱动器 api 调用。 错误:在驱动器

中创建文件时找不到文件

同样在全域授权之前,我通过与服务帐户共享一个驱动器文件夹使其工作。但现在我希望它在不共享的情况下工作。

我想我需要在某个地方做一些 setServiceAccount 的事情。不确定会在哪里发生。

const {google} = require('googleapis');
const auth = new google.auth.JWT(
    client_email, null,
    privateKey, ['https://www.googleapis.com/auth/drive']
);
const drive = google.drive({version: "v3", auth});
//drive.files.create({});

答案:

您需要将从 GCP 控制台获取的服务帐户私钥传递给您的 JWT 客户端,并指定您希望模拟哪个用户作为 subject

代码:

获取私钥后,需要在授权前将其传递给JWT Client:

let google = require('googleapis');
let privateKey = require("./privatekey.json");

var jwtClient = new google.auth.JWT({
       email: privateKey.client_email,
       key: privateKey.private_key,
       scopes: ['https://www.googleapis.com/auth/drive'],
       subject: 'user@domain.com'
    });

jwtClient.authorize(function (error, tokens) {
  if (error) {
    console.log(error);
    return;
  } 
  else {
    console.log("Successfully connected!");
  }
});

然后您可以使用 Drive API 作为服务帐户进行任何操作。