skip to Main Content

I’m trying to upload an image to AWS S3. This code previously worked fine (and still working for another project). This is a brand new project with a new AWS S3 bucket. I noticed they again changed a lot and maybe it’s a problem.

This is the code:

        s3_client.upload_fileobj(
            uploaded_file,
            files_bucket_name,
            key_name,
            ExtraArgs={
                'ContentType': uploaded_file.content_type
            }
        )

This is the permission policy for the bucket:

{
    "Version": "2012-10-17",
    "Id": "Policy1204",
    "Statement": [
        {
            "Sid": "Stmt15612",
            "Effect": "Allow",
            "Principal": "*",
            "Action": [
                "s3:GetObject",
                "s3:PutObject"
            ],
            "Resource": "arn:aws:s3:::bucket-name/*"
        }
    ]
}

The upload did not work until I added the "PutObject" here but it was working for another project. I don’t like about this policy that PutObject is now public available.

How to make:

  • all images are public available
  • but only owner can upload files?

This are screenshots from AWS permissions for this bucket:

Public

enter image description here

2

Answers


  1. Chosen as BEST ANSWER

    The problem has gone as soon as I created an IAM user and granted it full access to S3. Not sure if this solution is good or not but at least it's working now.


  2. It appears that your requirement is:

    • Allow everyone to see the files
    • Only allow an owner to upload them

    There is a difference between "seeing the files" — ListObjects allows listing of the objects in a bucket while GetObject allows downloading of an object.

    If you want to make all objects available for download assuming that the user knows the name of the object, then you could use a policy like this:

    {
        "Version": "2012-10-17",
        "Statement": [
            {
                "Effect": "Allow",
                "Principal": "*",
                "Action": [
                    "s3:GetObject"
                ],
                "Resource": "arn:aws:s3:::bucket-name/*"
            }
        ]
    }
    

    Note that this policy will not permit viewing the contents of the bucket.

    If you wish to allow a specific IAM User permission to upload files to the bucket, then put this policy on the IAM User (not on the Bucket):

    {
        "Version": "2012-10-17",
        "Statement": [
            {
                "Effect": "Allow",
                "Action": [
                    "s3:PutObject"
                ],
                "Resource": "arn:aws:s3:::bucket-name/*"
            }
        ]
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search