Amazon S3 – Restrict Access to S3 Bucket Folders to Specific Website Users

amazon s3amazon-iamamazon-web-servicesdatabase

I have a website where users need to log in. They can upload and delete their own pictures BUT these pictures are supposed to be private so images are not set to public that anyone can view.

I know that we can use IAM policies to restrict access to different folders in a S3 bucket to different IAM users. However the website users are just normal registered users recorded in the database (probably MySQL), they are not IAM Users.

What would be the logic to set this up without needing an IAM user for each website user? Are there any good examples that you can suggest? Or I am thinking too much that there's easier way to set this kind of restrictions?

Thanks in advance for any suggestions.

Best Answer

Another option is to get away without IAM roles and credentials altogether and use S3 Pre-signed URLs. With pre-signed URLs you can create a secure, time-limited image links that will enable unauthenticated access to otherwise private objects in S3. In other words:

  • Your S3 objects are all private, no one else than the webserver has access to them.
  • When the user logs in you generate pre-signed URLs for his images. These URLs will give the user temporary access to his content (e.g. with 1 hour validity).
  • When the link expires (after e.g. 1 hour) it no longer provides access to the user's image.

This way you can get away without any IAM users or IAM roles for the website users.

Here is a simple demo on how to implement it: S3 Pre-signed URL demo

You can also use pre-signed URLs for image uploads, but that's a bit more involved. It may be easier to upload the images to your server using the standard upload methods and the server uploads them to S3.

This is a more limited approach than using Cognito, but it may be easier to implement.

Hope that helps :)