node.js - Node : Fail to use service account to access Gmail API

标签 node.js gmail-api service-accounts

我有一个 G 套件域并开设了一个具有域范围委托(delegate)的服务帐户。服务帐户在项目中也具有所有者身份。 我启用 gmail API 并添加范围引用(https://developers.google.com/admin-sdk/directory/v1/guides/delegation“将域范围的权限委托(delegate)给您的服务帐户”) 我也启用了不太安全的应用程序设置。

这是我的代码:

var {google} = require('googleapis');

var jwtClient = new google.auth.JWT(
    "service@xxx.iam.gserviceaccount.com",
    null,
    "-----BEGIN PRIVATE KEY-----\n....",
    ['https://mail.google.com/', 
    'https://www.googleapis.com/auth/gmail.readonly', 
    'https://www.googleapis.com/auth/gmail.modify', 
    'https://www.googleapis.com/auth/gmail.metadata'] // I have also tried https://www.googleapis.com/auth/gmail.imap_admin
);

jwtClient.authorize(function(err, tokens) {
    if (err) {
      console.error(err);
      return;
    }
    console.log(tokens); // successful print the token
});

但是当我使用这个 token 尝试列出电子邮件时: 获取 https://www.googleapis.com/gmail/v1/users/me/messages?access_token= {access_token}

发生错误。

{
    "error":{
        "errors":[
            {
                "domain": "global",
                "reason": "failedPrecondition",
                "message": "Bad Request"
            }
        ],
        "code": 400,
        "message": "Bad Request"
    }
}

我不需要解决方法,我打算使用服务帐户解决问题。我成功地将 Gmail API 与其他身份验证选项结合使用。 我已经阅读了很多文章,但没有一篇有帮助。我坚持了一个星期,任何建议将不胜感激。

如果重要,我可以免费提供更多详细信息。

最佳答案

添加子声明应该可以解决这个问题。

var jwtClient = new google.auth.JWT(
    "service@xxx.iam.gserviceaccount.com",
    null,
    "-----BEGIN PRIVATE KEY-----\n....",
    ['https://mail.google.com/', 
    'https://www.googleapis.com/auth/gmail.readonly', 
    'https://www.googleapis.com/auth/gmail.modify', 
    'https://www.googleapis.com/auth/gmail.metadata'], // I have also tried https://www.googleapis.com/auth/gmail.imap_admin
    'user@yourdomain.com' // use a user email in your domain since service account do not have Gmail box
);

关于node.js - Node : Fail to use service account to access Gmail API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49937107/

相关文章:

python - 使用 Google Apps 服务帐户启用邮件转发

node.js - 如何从响应正文中检索参数

javascript - 谷歌SDK返回403 `User Rate Limit Exceeded`

node.js - 在 Angular 和 Node.js 项目之间共享代码

javascript - Gmail API 查询以检索在给定时间后发送的未读邮件

java - 使用 Gmail Java API 使用现有凭据创建 Gmail 实例

php - 谷歌服务帐户示例返回 "Error refreshing the OAuth2 token { “error” : “invalid_grant” }"

node.js - NODE ACL 模块生成 500 而不是 403

ios - 使用 Gmail API 获取消息

java - 尝试使用服务帐户进行身份验证时获取 "401 Unauthorized"