简体   繁体   中英

AWS S3 PutObject Access denied problem in Python

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:

上市

在此处输入图像描述

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.

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/*"
        }
    ]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM