Prince Joal
Software Engineer
  • Name: Prince

  • Birthday: 28 February 1993

  • Job: Freelancer

  • Email: [email protected]

  • Skype: 1081a1d198d8081c

How can I grant users access to S3 objects?

All objects are set to private by default, which means that only the bucket account owner has access to them at first. If you want a user to have access to a certain bucket or object without making it public and secure aws S3 upload object with node app, you can use an IAM policy to provide them the necessary permissions. You can build a presigned URL in s3 that allows users to interact with items without needing AWS credentials or IAM permissions, in addition to providing access via an IAM policy.

So, what exactly are presigned URLs & how secure aws S3 upload object with node app?

An S3 presigned URL can be used to offer temporary access to a particular S3 item to your users. An object can be read or written using the URL (or update an existing object). Your application’s parameters are included in the URL. The user’s access is restricted by three parameters in a pre-signed URL;

  • Bucket : The Name of bucket in which the object is stored (or will be in).
  • Key : The name of the object or path like eg: dir1/dir2/file.png or file.png.
  • Expires : The URL is valid for a certain amount of time, measured in seconds.

As expected, the user would be unable to interact with the given object once the expiration time has passed. Because the URL can only be signed properly by the S3 Bucket owner, AWS grants access to the item through the presigned URL.The objects may be accessed by anybody with a valid pre-signed URL, as provided during the creation process. For example, a user could not utilise a pre-signed GET (Read) URL as a PUT (Write).

 

The AWS JS SDK automatically generates the URL’s numerous parameters, which are used in the URL’s structure. These are a few examples:

  • X-AMZ-Algorithm
  • X-AMZ-Credential
  • X-AMZ-Date
  • X-AMZ-Expires
  • X-AMZ-Signature
  • X-AMZ-SignedHeaders
<?php

https://presignedurldemo.s3.eu-east-1.amazonaws.com/image.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=ASIAFGDZ7B6WWEGMKFTR%2F20180210%2Feu-east-1%2Fs3%2Faws4_request&X-Amz-Date=20180210T171315Z&X-Amz-Expires=1800&X-Amz-Signature=73bn45b3vh3jk4kj3a036bc7c3d03b3f20c61f1f91cc9ad8873e3314255dc479a276345&X-Amz-SignedHeaders=host

An example of a URL that can be used to retrieve objects is shown above. The link is no longer valid because the maximum period before a presigned URL expires is 7 days.

If so, how do I go about creating a pre-signed URL?

Creating an IAM user with permissions to read and write S3 objects is the first stage. Next, an API key for the IAM user will be generated and saved as an environment variable on the server.

  1. Create a bucket in S3 by going to the site. Ensure that the bucket name is not already taken by someone else.
  2. Navigate to the IAM section.
  3. To provide programmatic access, create a user account.
  4. Go to the next step: Permissions
  5. Create a new policy by selecting the box next to Attach current policies directly.
  6. To pick the S3 service, go to the visual editor and click on it. Expand the access level groups to fit just a few of our needs.
  7. In the READ section, make sure that GetObject and PutObject are both checked.
  8. Set the resources you wish to allow access to; choose the bucket name you established earlier and the object name by selecting Any.
  9. Click on Review Policy and give the policy a name. The policy can be saved.

Review Policy

To access AWS, you will need to utilise the newly established user account and the new policy that you just applied to it.

Creating node express app for pre-signed url for s3 bucket

  1. Create a new folder in visual code
  2. To install a node module which linked to a package.json, do “npm init” in the terminal
  3. Now run “npm install express —save” to install Express in the specified directory.
  4. Use the command “npm install aws-sdk —save” to install aws npm.
  5. Create new file file name “app.js”visual code presigned url secure aws S3 upload object with node app
<?php

const express = require('express');
const aws=require('aws-sdk');
const app = express();
const port = 3000;
const BUCKET_NAME = 'presigned-url-demo-bucket-name';
const accessKeyId='AHG678JH78GCZA3HUZ78HG';
const secretAccessKey='jghg323gjnn8dW2ybYASKAD9lsdfhj242321j23gh';

aws.config.update({
    region: 'us-east-1',
    accessKeyId,
    secretAccessKey
});
const s3=new aws.S3();
app.get('/', async (req, res) => {
    const url= await s3.getSignedUrlPromise('getObject',{
        Bucket: BUCKET_NAME,
        Key: 'img1.png',
        Expires: 60
    });
    console.log({url});
  res.send('url'+url)
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

POST URL Parameters for secure aws S3 upload object with node app

This article provides a high-level summary of the needed parameters; however, AWS Documentation provides a more detailed discussion of all parameters;

https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-HTTPPOSTConstructPolicy.html

  • Bucket: process.env.S3_BUCKET (The bucket name)
  • Expires: 1800 (Time to expire in seconds (30m))
  • key: ‘image.jpg’ (Filename)
  • { acl: ‘private’ } (It defines which AWS accounts or groups are granted access and the type of access.)
  • { success_action_status: “201” } (HTTP status code returned if successful)
  • [‘starts-with’, ‘$key’, ”] (The value must start with the specified value (e.g. ‘user1/’. In our case image has no additional prefix ‘’)
  • [‘content-length-range’, 0, 100000] (Specify the range of the content you are uploading in Bytes)
  • {‘x-amz-algorithm’: ‘AWS4-HMAC-SHA256’} (Specify the signing algorithm used during signature calculation)

S3 Buckket object

s3-buckket

To prevent an unauthorised person from accessing sensitive information, turn on “Block all public access.”

secure aws S3 upload object with node app

AWS SDK S3 Documentation:

https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html

Download aws-s3-presigned Script 

🙂 I really hope that you have grasped the concept of utilising a presigned url to protect an S3 object in Node JS.

Tags: S3 bucket

5 2 votes
Article Rating
Subscribe
Notify of
guest

6 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
avneet kumar

Great learning, Really concept clearing article

himanshu

good read. thanks for sharing

Priyanka

Great insight.

Neha

Detailed knowledge I’d love to read more on this.

Hrithik Rana

Wow. Knowledgeable content.

Bhupinder

Good Read. Very knowledgeable ✌️

Sarvesh

Great Article.

6
0
Would love your thoughts, please comment.x
()
x