简体   繁体   中英

Django/AWS - An error occurred (403) when calling the HeadObject operation: Forbidden

I'm trying to set up my Django project to host static images on AWS S3 buckets, but when I try to upload an image via the Django admin panel I get the following error

在此处输入图像描述

These are my settings in Django

AWS_ACCESS_KEY_ID = 'some_key' 
AWS_SECRET_ACCESS_KEY = 'some_key_aswell' 
AWS_STORAGE_BUCKET_NAME = 'bucket_name'

AWS_S3_FILE_OVERWRITE = False
AWS_DEFAULT_ACL = None
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'

AWS_S3_REGION_NAME = 'us-east-2' 

Cors policy setup for the bucket

 [
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "GET",
            "POST",
            "PUT"
        ],
        "AllowedOrigins": [
            "*"
        ],
        "ExposeHeaders": []
    }
]

The IAM role used by the machine (or container) on which your Django app runs needs the following IAM policy added:

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

If your object is encypted, make sure that you also allow your IAM role to use the KMS key used to encrypt your object.

I went over and changed the Bucket policy to this:

{
    "Version": "2008-10-17",
    "Statement": [
        {
            "Sid": "AllowPublicRead",
            "Effect": "Allow",
            "Principal": {
                "AWS": "*"
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::YOUR-BUCKET-NAME/*"
        }
    ]
}

And it worked.

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