'S3 permission for hosting public images for a web app

I've started using S3 to host images connected to Rails models. Images are not uploaded by users so I just use aws_sdk gem to store images to S3 buckets.

So far I've succeeded in storing the image, but I am confused about the permission. Maybe I'm wrong but it seems most of the documents talking about S3 permission are outdated and I can't find what they are referring to.

What I want to do is pretty basic. I just want to host images and the image themselves are public so anyone can view. However I don't want anyone to just access my bucket and see everything else that's hosted there. So basically it's just a normal web app that hosts images on S3. How and where can I change the permission settings so it works that way? Currently the access is only granted to myself and images are not viewable by typing the url in a browser.



Solution 1:[1]

Take a look at the docs, more specific at the S3Objects write method: Class: AWS::S3::S3Object, which allows you to set a bunch of options for the uploaded file.

When uploading to your S3 bucket you have so set the proper :acl permission, because its default is :private and no public access is granted. Here's a modified snippet I grabbed from github:

# get an instance of the S3 interface using the default configuration
s3 = AWS::S3.new

# create a bucket
b = s3.buckets.create('example')

# upload a file
basename = File.basename('image.png')
o = b.objects[basename]
o.write(:file => file_name,  :acl => :public_read)

# grab public url
image_public_url = o.public_url

...

Solution 2:[2]

For people that are looking for more specific information on how to write a policy that allows anyone to access an s3 bucket this may be helpful.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicRead",
            "Effect": "Allow",
            "Principal": "*",
            "Action": [
                "s3:GetObject",
                "s3:GetObjectVersion"
            ],
            "Resource": [
                "arn:aws:s3:::DOC-EXAMPLE-BUCKET/*"
            ]
        }
    ]
}

This, and other examples at, the link below.

https://docs.aws.amazon.com/AmazonS3/latest/userguide/example-bucket-policies.html#example-bucket-policies-use-case-2

If your are still having issues, check your block settings.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dom
Solution 2 Daniel Illenberger