node.js - 如何使用服务帐户访问 GSuite 电子邮件帐户的 GMAIL API

标签 node.js gmail-api google-api-client google-api-nodejs-client

我希望我的服务帐户能够模拟 GSuite 中的一位用户。 我有

  • 通过 GCP 创建了一个项目
  • 在项目中启用了 GMail API
  • 向该项目添加了一个服务帐户
  • GCP 的服务帐户设置中启用了全域委派
  • 通过 Google 管理面板为 GSuite 在高级设置中添加了带有 服务帐户 IDAPI 客户端

在浏览文档(java)时,我看到了这个

GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream("MyProject-1234.json"))
    .createScoped(Collections.singleton(SQLAdminScopes.SQLSERVICE_ADMIN))
    .createDelegated("user@example.com");

他们在这里指定服务帐户应该模拟哪个用户。此代码在 java 中。我需要在 nodejs 中完成同样的事情。

在浏览 googleapisnodejs-client 文档时,我发现了这个:

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

const auth = new google.auth.GoogleAuth({
  keyFile: '/path/to/your-secret-key.json',
  scopes: ['https://www.googleapis.com/auth/cloud-platform'],
});

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

const oauth2Client = new google.auth.OAuth2(
  YOUR_CLIENT_ID,
  YOUR_CLIENT_SECRET,
  YOUR_REDIRECT_URL
);

// set auth as a global default
google.options({
  auth: oauth2Client
});

这里的GoogleAuthOAuth2有什么区别?

如何设置所有内容以便我的 node.js 应用程序可以通过服务帐户访问 user@abc.xyz 邮件?

如何指定要通过服务帐户访问的电子邮件

最佳答案

documentation指定:

Rather than manually creating an OAuth2 client, JWT client, or Compute client, the auth library can create the correct credential type for you, depending upon the environment your code is running under.

换句话说:

  • google.auth.GoogleAuth 是一个库工具,如果您不知道自己需要哪些凭据,它会为您动态创建正确的凭据
  • google.auth.OAuth2 始终专门创建 OAuth2 凭据
  • 对于您以自己身份进行身份验证的大多数应用程序,您需要 OAth2
  • 但是要使用服务帐户,您需要创建一个 JSON Web Token 指定的 here
  • 仔细检查您是否创建了 service account crendetials ,最好作为 json 文件,启用 domain-wide delegation并向服务帐户提供必要的 scopes在管理控制台中。
  • 要在您的代码中实现模拟,请在创建 JWT 客户端时添加 subject: USER_EMAIL 行。

示例

const {JWT} = require('google-auth-library');
//THE PATH TO YOUR SERVICE ACCOUNT CRENDETIALS JSON FILE
const keys = require('./jwt.keys.json');

async function main() {
  const client = new JWT({
    email: keys.client_email,
    key: keys.private_key,
    scopes: ['YOUR SCOPES HERE'],
    subject: USER_EMAIL
  });
  const url = `https://dns.googleapis.com/dns/v1/projects/${keys.project_id}`;
  const res = await client.request({url});
  console.log(res.data);
}

main().catch(console.error);

关于node.js - 如何使用服务帐户访问 GSuite 电子邮件帐户的 GMAIL API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62848002/

相关文章:

android - 使用 Google API 进行后台位置更新 - Fused Location Provider 不准确

mysql - 池不断增加连接并以 ER_CON_COUNT_ERROR 结束

javascript - 在异步函数中等待 MySQL 查询?

google-api - Gmail API 推送通知重复消息 ID

javascript - Google 脚本匹配正则表达式

javascript - 使用 Javascript 解码 Google Oauth2 访问 token

javascript - Angular 页面不显示来自 Node 后端的 JSON 数据

javascript - 如何编辑 React 组件并更改屏幕上显示的文本

php - 在 php 中使用 gmail api 发送带附件的邮件

android - 在 Play Services 8.3 的新谷歌登录中获取个人详细信息