Search code examples
amazon-s3mongodb-stitch

How to get AWS S3 signed URL with mongoDB Stitch?


I'm trying to retrieve some files from a S3 bucket, but the files are setup to be private. I'm currently using ListObjects to retrieve all the files in my bucket, but on the result set it does not include the signed url and since the file is private I cannot display it on my website.

I'm using mongoDB Stitch to connect to my S3 bucket.

Here my code that retrieves all the files in my bucket.

const aws = this.client.getServiceClient(AwsServiceClient.factory, "TESTAPP");
const args = {
   Bucket: bucketName,
   Prefix: folderName
};

const request = new AwsRequest.Builder()
   .withService('s3')
   .withAction('ListObjects')
   .withArgs(args);

aws.execute(request.build())
    .then(result => {
        console.log(result);
    }

When I look at the console.log I can see all the file information but the I try to access the file since it is a private file I get an error saying I do not have access to it.

Do I need to make another call to get the signed url or is it possible to get all at once?


Solution

  • So you have a few options.

    1. If you’re publicly displaying the images, then just make them public on amazon. If you turn list option off in the permissions on Amazon for those images, then people would need the exact url to view it so it's not like random people on the internet will be going through your photos. So unless it's actually sensitive data, this option might be fine.

    2. You can use the GetObject method with the Stitch sdk. This will give you back the base64 version of the image. Then you can either convert it to an image or embed the base64 directly into the src of an <img> tag in your html which would look something like

    <img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA
        AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
        9TXL0Y4OHwAAAABJRU5ErkJggg==" />

    1. You can sign the GET request with your AccessKeyId and Signature as query parameters. This link will show you how to create the signature.