Search code examples
phpamazon-web-servicesamazon-s3flysystem

AWS S3 - storing and serving non-private images


I am, for the first time, implementing file uploads using S3 (in this case specifically user profile avatar images) using Flysystem. I'm currently at the point where I have created an S3 bucket, and a user can upload an image, which is then visible online in the bucket console.

I now need the ability to display those images when requested (i.e. viewing that user's profile). I assumed that the process for this would be to generate the URL (e.g https://s3.my-region.amazonaws.com/my-bucket/my-filename.jpeg) and use that as the src of an image tag however to do this, the file (or bucket) must be marked as public. This seemed reasonable to me because the files within are not really private. When updating the bucket to public status however you are presented with a message stating;

We highly recommend that you never grant any kind of public access to your S3 bucket.

Is there a different, or more secure, way to achieve direct image linking like this that a newcomer to AWS is not seeing?


Solution

  • The warning is there because many people unintentionally make information public. However, if you are happy for these particular files to be accessed by anyone on the Internet at any time, then you can certainly make the individual objects public or create an Amazon S3 bucket policy to make a particular path public.

    The alternative method to granting access is to create an S3 Pre-Signed URL, which is a time-limited URL that grants access to a private object.

    Your application would be responsible for verifying that the user should be given access to a particular object. It would then generate the URL, supplying a duration for the access. Your application can then insert the URL into the src field and the image would appear as normal. However, once the duration has passed, it will no longer be accessible.

    This is typically used when providing access to private files -- similar to how DropBox gives access to a private file without making the file itself public.