【问题标题】:NodeJS: Fail to use service account to access Gmail APINodeJS:无法使用服务帐户访问 Gmail API
【发布时间】:2018-09-30 21:40:54
【问题描述】:

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

这是我的代码:

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

但是当我使用此令牌尝试列出电子邮件时: 获取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 与其他身份验证选项一起使用。 我读过很多文章,但没有一篇有帮助。我已经坚持了一周,任何建议将不胜感激。

如果有问题,我会随时提供更多细节。

【问题讨论】:

    标签: node.js gmail-api service-accounts


    【解决方案1】:

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

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

    【讨论】:

    • 我试过了......有点失败......蚂蚁额外的技巧? (我的服务帐户具有域范围内的授权 w 论文处理)完全相同的参数...(我的域中的例外用户帐户)并且我得到:错误:未授权客户端:客户端未经授权使用此方法检索访问令牌。 ... tnaks 反馈:
    猜你喜欢
    • 2022-01-15
    • 1970-01-01
    • 2014-09-06
    • 2014-09-13
    • 2020-11-01
    • 2013-03-28
    • 2015-05-14
    • 2019-01-10
    • 1970-01-01
    相关资源
    最近更新 更多