Node.js 使用 AWS EC2 IAM 角色凭证获取 signedurl

Node.js get signedurl with AWS EC2 IAM Role Credentials

在我的 Node.js 项目中,我需要在 S3 中使用 AWS IAM 角色获得签名 url。获得url的部分是这样的

            url = s3.getSignedUrl('getObject', {
                Bucket: myBucket,
                Key: myKey,
                Expires: signedUrlExpireSeconds
            })

然后我设置了这样的值

var AWS = require('aws-sdk');

AWS.config.update({signatureVersion: 'v4',
region: 'us-east-1'});
AWS.config.credentials = new AWS.EC2MetadataCredentials();
var s3 = new AWS.S3();

当我 运行 这个 url 我得到的总是只是 https://s3.amazonaws.com/

但是如果我设置像这样硬编码的凭据,而不是使用 AWS.config.credentials = new AWS.EC2MetadataCredentials();,那么它 returns 正确的 url

s3.config.update({
    accessKeyId: 'xxx',
    secretAccessKey: 'yyy',
});

据此,https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/loading-node-credentials-iam.html 它应该自动获取凭据而无需像上面那样设置。 如果不直接在代码中提供 accesskey 和 secrectkey,你能告诉我做错了什么以及为什么它不起作用吗?

同样在我们的 Java 项目中,它在不指定这些键的情况下也能正常工作。但它在 Node.js.

中不起作用

这是为我工作的 nodejs 代码。我不必传递凭据或任何签名版本配置。

const getPresignedUrl = async (fileName, fileType) => {
  const s3 = new AWS.S3();  // Create a new instance of S3

  // Set up the payload of what we are sending to the S3 api
  const s3Params = {
    Bucket: S3_BUCKET,
    Key: fileName,
    Expires: 5000,
    //ContentType: fileType,
    // ACL: 'public-read',
    ContentType: 'application/octet-stream'
  };
  // Make a request to the S3 API to get a signed URL which we can use to upload our file

  try {
    const data = await s3.getSignedUrlPromise('getObject', s3Params);
    const returnData = {
      signedRequest: data,
      url: `https://${S3_BUCKET}.s3.amazonaws.com/${fileName}`
    };

    return returnData;

  } catch (err) {
    console.log('err: ', err);
  }
}

希望对您有所帮助