Anralore
Anralore

Reputation: 123

s3 pre-signed url Javascript Code not Returning Full url

I am trying to generate pre-signed url's for files in my s3 bucket so that users of my site will not have the links to the actual files. I have been trying to use this code below:

const AWS = require('aws-sdk');
const s3 = new AWS.S3()
    AWS.config.update({accessKeyId: 'AKIAVXSBEXAMPLE', secretAccessKey: 'EXAMPLE5ig8MDGZD8p8iTj7t3KEXAMPLE'})

    // Tried with and without this. Since s3 is not region-specific, I don't
    // think it should be necessary.
    AWS.config.update({region: 'eu-west-2'})

    const myBucket = 'bucketexample'
    const myKey = 'example.png'
    const signedUrlExpireSeconds = 60 * 5

    const url = s3.getSignedUrl('getObject', {
        Bucket: myBucket,
        Key: myKey,
        Expires: signedUrlExpireSeconds
    })
    setTimeout(function(){ console.log("url", url); }, 3000);
    console.log("url:", url)

However all it returns is this: "https://s3.amazonaws.com/"

I have also tried using this code:

const AWS = require('aws-sdk');
var s3 = new AWS.S3();
    var params = {Bucket: 'bucketexample', Key: 'example.png'};
    s3.getSignedUrl('putObject', params, function (err, url) {
       console.log('The URL is', url);
    });

Which does not return anything. Does anyone know why they are not returning a working urls?

Upvotes: 3

Views: 2947

Answers (2)

Ankur Gupta
Ankur Gupta

Reputation: 23

I had similar issue where I was getting incomplete signed URL like when I used :

    let url = await s3.getSignedUrl("getObject", {
  Bucket: bucket,
  Key: s3FileLocation,
  Expires: ttlInSeconds,
});

Then I used the Promise function instead :

// I used it inside an async function

let url = await s3.getSignedUrlPromise("getObject", {
  Bucket: bucket,
  Key: s3FileLocation,
  Expires: ttlInSeconds,
});

And it returned complete signed URL.

Note:

In case you receive this message on tryign to access the object using signed URL.

    <Error>
<Code>InvalidArgument</Code>
<Message>Requests specifying Server Side Encryption with AWS KMS managed keys require AWS Signature Version 4.</Message>

Then use this while initializing s3 :

const s3 = new AWS.S3({"signatureVersion":"v4"});

Upvotes: 2

danielv123
danielv123

Reputation: 318

I've had a similar issue. When the AWS SDK returns https://s3.amazonaws.com/ it is because of the machine not having the proper permissions. This can be frustrating, and I think that AWS should return a descriptive error message instead of just returning the wrong url.

I would recommend that you configure your AWS credentials for your machine or give it a role in AWS. Although you should be able to put in your credentials via code like you did in your code snippet, that didn't work for me as well for whatever reason.

What worked for me was updating my machine's default AWS credentials or adding proper roles for the deployed servers.

Upvotes: 3

Related Questions