如何获得完整的 SendGrid API Key?

How to get the full SendGrid API Key?

我能够从 web app 获得一个 API 密钥。但是,根据 SendGrid 文档,我只能访问整个密钥的一小部分。

如果您看到下面的 API 密钥示例:

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

子字符串 "ngeVfQFYQlKU0ufo8x5d1A" 是 API 键。

这些东西的其余部分是什么?他们是如何生成这个 entire/full 字符串的?

参考:SendGrid Docs - API Keys


* 已解决 *

API KEY 生成并显示给您一次。所以一定要复制并保存在某个地方。之后只显示子集键。

API KEY 仅生成并显示给您一次。所以一定要复制并保存在某个地方。之后只显示子集键。

它在 here 的文档中被提及为 warning/alert。

The sub-string "ngeVfQFYQlKU0ufo8x5d1A" is the API Key.

您指的子字符串 不是 API 密钥,它是 API 密钥 ID。

What is the rest of this stuff and how did they generate this entire/full string?

完整字符串是整个API键,分为3段,用分隔。所以 API KEY = SG.ID.VALUE:

  • SG:在每个 SG API 键的开头附加一个固定值,我假设 SG 代表 "SendGrid".
  • ID:这是通过API编辑和删除key时用来引用的key ID,不是真正的key。因此,如果这是您的 API 密钥:SG.aaaa.bbbb,则 api_key_id 将是 aaaa.
  • VALUE:这是您只允许阅读一次的键值

How to get the full SendGrid API Key?

只有两种方法可以做到;通过SendGrid UI或API。两者都在创建时访问,您只能读取键值一次

  • API:为了从 API 创建和读取密钥,您需要事先访问 API,这意味着您需要使用 SendGrid UI 创建一个初始 API 密钥。之后,您可以 POST to /api_keys.

这是一个使用 official SendGrid web API v3 client via Node.js:

的例子
import sgClient from '@sendgrid/client';

/** Your initial API key from the SendGrid UI */
sgClient.setApiKey(process.env.SENDGRID_API_KEY);

let req = {
  method: 'POST',
  url: '/v3/api_keys',
  body: { name: 'NEW_SG_KEY' }
};

sgClient.request(req)
  .then( ([res, body]) => {
    console.log(`key: ${body.api_key}`);
    console.log(`ID:  ${body.api_key_id}`);
  })
  .catch( err => {
    console.log(`Unable to create new API key: ${err.code} ${err.message}`);
  });