Why can't I get images from my S3 bucket when all public access blocked? 403 Forbidden But static files load fine

Viewed 618

My Django website allows users to upload photos. When the s3 bucket is on public the media content loads fine on the site. However once i block all public access the content no longer loads and a 403 forbidden error is shown. In my code I have added the values needed to allow for authenticate requests. There are no bucket policy's or any CORS configurations. I have tried several different suggestions from blogs and tutorials but nothing seems to work.

I have a user which has programmatic access and set the secret variables in the heroku environment and still get 403 error. I have tried hard setting the secret variables and still no success.

settings.py

AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME')

AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
AWS_S3_OBJECT_PARAMETERS = {
    'CacheControl': 'max-age=86400',
}

MEDIA_LOCATION = 'MediaStorage'
MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIA_LOCATION)
MEDIA_FILE_STORAGE = 'MediaStorage'

STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATIC_LOCATION = 'static'
STATICFILES_LOCATION = 'StaticStorage'
STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATIC_LOCATION)

django_heroku.settings(locals())

storage_backends.py

from storages.backends.s3boto3 import S3Boto3Storage
from django.conf import settings

class StaticStorage(S3Boto3Storage):
    location = settings.STATICFILES_LOCATION

class MediaStorage(S3Boto3Storage):
    location = settings.MEDIA_FILE_STORAGE
    file_overwrite = False
    custom_domain = False

All static files load fine but media files do not load at all. I expect the files to load when displaying them in the view web page. however i just get a 403 forbidden error.

2 Answers

In your settings.py your have set?

AWS_DEFAULT_ACL = 'public-read'

Look this example is an public project for my state in Brazil.

Project

So after many iterations it came down to a line of code missing in the storage_backends.py file missing the line custom_domain = False

I have updated the original post to match the correct storage_backends.py file

Related