I have a dockerized Django app that utilizes Gunicorn and Nginx. When logging in on the admin page using localhost, no CSRF error emerges. When running the docker on Amazon EC2 with Route 53 as the proxy server (https redirects to http), I get the CSRF error on login. I note the following in my settings.py file (I added the SECURE_SSL_REDIRECT = False but it has had no effect):
ALLOWED_HOSTS = ['localhost', '.website_name.ca']
SECURE_SSL_REDIRECT = False
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'The6ixDjango.apps.The6IxdjangoConfig',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
Given that I have Route 53 on the front-end, is it 'safe' to remove the csrf middleware reference in the MIDDLEWARE list?
Since you're using a proxy that translates https requests into http, you need to configure Django to allow POST requests from a different scheme (since Django 4.0) by adding this to settings.py
:
CSRF_TRUSTED_ORIGINS = ["https://yourdomain.com", "https://www.yourdomain.com"]
If this does not solve your problem, you can temporarily set DEBUG = True
in production and try again. On the error page, you will see a "Reason given for failure" that you can post here. (You write about "the CSRF error on login" but there are 9 possible errors, it would be useful to know the actual error.)
SECURE_SSL_REDIRECT
should be False
indeed (since Route 53 will handle the redirect for you) but False
is the default value so you can simply omit the SECURE_SSL_REDIRECT
setting.
It is definitely not safe to remove CsrfViewMiddleware
from the MIDDLEWARE
list. Route 53 will not give you an equivalent protection against CSRF-attacks.