且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

nodejs 中 lambda 函数内的 AWS IAM 授权

更新时间:2023-08-18 16:48:28

我们需要使用三个附加参数构建常规的 nodejs 请求选项

We need to build regular nodejs request options with three additional parameters

服务:API网关的execute-api"

区域:us-east-1" AWS 区域.

body: postData ,通常我们传递body req.write,我们在options中也需要它,因为它是签名所必需的.

body: postData , typically we pass body req.write, we also need it in options because it is needed for signing.

最后将 aws4.sign(...) 传递给 request.

所有 .sign 方法所做的就是添加 4 个额外的标头 X-Amz-Content-Sha256X-Amz-Security-TokenX-Amz-DateAuthorization

All .sign method does is adds 4 additional headers X-Amz-Content-Sha256, X-Amz-Security-Token, X-Amz-Date and Authorization

var aws4 = require("aws4");
var https = require("https");

const requestBody = { name: "test" };
var postData = JSON.stringify(requestBody);

var options = {
  method: "GET",
  hostname: "abcdefgh.execute-api.us-east-1.amazonaws.com",
  path: "/status",
  headers: {
    "Content-Type": "application/json",
  },
  service: "execute-api",
  region: "us-east-1",
  body: postData,
  maxRedirects: 20,
};

const signedRequest = aws4.sign(options, {
  secretAccessKey: "abcadefghijknlmnopstabcadefghijknlmnopst",
  accessKeyId: "ABCDEFGHIJKLMNOPQRST",
  sessionToken: "this is optional ==",
});
console.log(signedRequest);
var req = https.request(signedRequest, function (res) {
  var chunks = [];

  res.on("data", function (chunk) {
    chunks.push(chunk);
  });

  res.on("end", function (chunk) {
    var body = Buffer.concat(chunks);
    console.log(body.toString());
  });

  res.on("error", function (error) {
    console.error(error);
  });
});
req.write(postData);
req.end();

由于此调用是从 lambda 整个对象进行的,键可以跳过,只需调用 aws4.sign(options),它应该从环境变量中使用.

since this call is made from lambda whole object with keys can be skipped and simply call aws4.sign(options), it should use from environment variables.