1

In my Node.js project I need to get a signed url in S3 with AWS IAM role. The part for getting the url is like this

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

And I set the values like this

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();

When I run this the url I get is always just https://s3.amazonaws.com/

But if I set the credentials hard coded like this, instead of using AWS.config.credentials = new AWS.EC2MetadataCredentials();, then it returns the correct url

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

According to this, https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/loading-node-credentials-iam.html it should automatically get the credentials without setting like above. Can you please tell what I have done wrong and why it is not working without giving the accesskey and secrectkey directly in the code.

Also in our Java project it works fine without specifying these keys. But it is not working in Node.js.

Madhu
  • 1,209
  • 2
  • 22
  • 28

1 Answers1

1

here is the nodejs code thats working for me. I didn't have to pass credential or any signature version configs.

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);
  }
}

Hope this helps

Arun Kamalanathan
  • 8,107
  • 4
  • 23
  • 39