gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 01:11:36 26 4
gpt4 key购买 nike

我希望我的服务帐户能够模拟 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 Computeclient, the auth library can create the correct credential type foryou, 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com