NodeJS: 使用服务账户访问Gmail API失败

3
我有一个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
});

但是当我使用这个令牌尝试列出电子邮件时: GET 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。 我已经阅读了很多文章,但是它们都没有帮助我。我已经卡在这个问题上一周了,非常感谢任何建议。 如果需要,我可以提供更多详细信息。
1个回答

4
添加一个子声明应该可以解决这个问题。
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
);

3
我尝试了一下,但是失败了。我使用了与之前相同的参数(除了用户帐户是我的域中的),我的服务帐户拥有这些范围的域宽授权,还有其他技巧吗?我收到了错误消息:unauthorized_client: Client is unauthorized to retrieve access tokens using this method. 谢谢反馈。 - user762579

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接