【问题标题】:How to connect my G-Suite in nodejs server using Gmail API如何使用 Gmail API 在 nodejs 服务器中连接我的 G-Suite
【发布时间】:2020-10-23 00:36:41
【问题描述】:

我想使用 Gmail API 在 nodejs 服务器中访问我的 G-Suite 帐户。 我知道我应该创建服务帐户并使用其凭据进行身份验证。 我尝试了许多示例和方法,但无法使其发挥作用。

这是我最后一次尝试。 返回 400 错误请求。

代码:400, 错误:[ { 域:'全球', 原因:'失败的前提条件', 消息:'错误请求' } ]

const {GoogleAuth} = require('google-auth-library');
const credentials = require('./sevice-account-credentials.json');

async function main() {
    const clientEmail = credentials.client_email;
    const privateKey = credentials.private_key;
    if (!clientEmail || !privateKey) {
        throw new Error(`
      The CLIENT_EMAIL and PRIVATE_KEY environment variables are required for
      this sample.
    `);
    }
    const auth = new GoogleAuth({
        credentials: {
            client_email: clientEmail,
            private_key: privateKey,
        },
        scopes: 'https://mail.google.com/',
    });
    const client = await auth.getClient();
    const projectId = await auth.getProjectId();
    const url = `https://www.googleapis.com/gmail/v1/users/my-gsuite@domain.co.il/labels/label_id`;
    const res = await client.request({url});
    console.log(res.data);
}

main().catch(console.error);

【问题讨论】:

  • 请编辑您的问题并包含完整的错误消息。在你做任何事情之前,你需要设置domain wide deligation
  • 谢谢。我已经添加了错误。域范围的委派设置为 true。
  • 只是为了说清楚:域范围的委派是真的,仍然会抛出这个错误。
  • 嗨,我发布了一个关于这个的答案。您能否澄清一下这是否解决了您的问题?

标签: node.js google-api gmail-api service-accounts google-api-nodejs-client


【解决方案1】:

问题:

您没有冒充域中的任何帐户。这就是全域委派的重点:冒充/代表另一个帐户。

解决方案:

您必须通过在实例化GoogleAuth 时提供属性clientOptions 来指定您希望服务帐户代表哪个帐户:

clientOptions: { subject: "my-gsuite@domain.co.il" }

所以它会是这样的:

    const auth = new GoogleAuth({
        credentials: {
            client_email: clientEmail,
            private_key: privateKey,
        },
        scopes: 'https://mail.google.com/',
        clientOptions: { subject: "my-gsuite@domain.co.il" }
    });

参考:

【讨论】:

  • 解决了!非常感谢!
  • @mabruk 不客气!很高兴您的问题得到了解决。
猜你喜欢
  • 2020-10-25
  • 2019-04-14
  • 1970-01-01
  • 2018-06-19
  • 2011-04-15
  • 2018-11-05
  • 1970-01-01
  • 2017-08-11
  • 2020-05-27
相关资源
最近更新 更多