我有一个 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/