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.
Related
I faced an issue with a CORS policy and cannot see what is wrong.
I use Django framework and my static files are hosted in Azure Blob
So I am getting errors for these files and it says tuat Access-Control-Allow-Origin is not present:
What is strange that other files from the same host are loaded..
CORS settings looks like this:
ALLOWED_HOSTS = ['https://support.mdesk.lt', 'https://suppaccountstorage.blob.core.windows.net']
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = (
'https://support.mdesk.lt',
'https://suppaccountstorage.blob.core.windows.net',
)
CSRF_TRUSTED_ORIGINS = ['https://support.mdesk.lt']
INSTALLED_APPS = [
'corsheaders',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'django.contrib.humanize',
'bootstrap4form',
'supportSystem',
'storages'
]
SITE_ID = 1
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'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',
]
Wham am I doing wrong?
Loading fonts from a different origin is affected by the CORS settings (your CSS files seem to be fine). Since your assets are not served by the Django application but by the Azure storage you need to adjust the CORS settings there (they will not be processed by the Django middleware you are using). You can change the settings in the Azure Portal.
I'm using react on the frontend side and Django on the backend. I using django-cors-headers
for managing CORS in my Django app.
I have added the package in INSTALLED_APPS like this:-
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework.authtoken',
'rest_framework',
'corsheaders',
'services',
'feeds',
'knox',
'users',
]
then I have also added same in MIDDLEWARE
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'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',
'django.middleware.common.CommonMiddleware',
]
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
ALLOWED_HOSTS = ['*']
and I'm passing CORS headers from my client-side React app like:-
const Axios = axios.create({
baseURL: `${BASE_URL}/api`,
timeout: 1000,
headers: {
'X-Custom-Header': 'foobar',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
}
})
Error on frontend:-
Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/register' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.
Access-Control-Allow-Origin header is sent by server, not by frontend. Server also does not send this header always. Whenever client sends origin header, only then server sends Access-Control-Allow-Origin and when origin is not matched, CORS error in thrown. If you used create-react-app to bootstrap your react project, they have really nice documentation how to configure proxy, that way you dont have to configure CORS on backend. In django configuration try to remove ALLOWED_HOSTS = ['*'] line, CORS_ORIGIN_ALLOW_ALL = True should work for all.
there was a bug in my client-side headers'X-Custom-Header': 'foobar', after removing it started working fine
It's basically this question: cross origin access issues - django 2.1.7
But it's still not correctly answered. Is this still a JS thing? Or are we missing something?
The original question:
I have gone through literally all SO links, reinstalled django and django-cors-headers and followed this to the T and yet we get
pre flight error cross origin not allowed
Django version 2.1.7
relevant sections of settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders',
'uploads.core',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'corsheaders.middleware.CorsPostCsrfMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CORS_ORIGIN_ALLOW_ALL = True
Even with corsheader middlewear at the top, same error code arrives.
[Error] Cross-origin redirection to https://a.tile.openstreetmap.org/14/4684/6268.png denied by Cross-Origin Resource Sharing policy: Origin http://localhost:8000 is not allowed by Access-Control-Allow-Origin.
[Error] Cannot load image http://a.tile.openstreetmap.org/14/4684/6268.png due to access control checks.
It seems like the only way is to simply Disable Cross-Origin Security. You can look it up on Google; I'm not sure if you still need CORS middlewear for production (i.e. hosted, deployed, served via url) however.
I'm having a problem with the csrf token on a Django powered site, which I'm close to reporting as a bug.
Problem is basically, CSRF token fails when DEBUG is False. When DEBUG is False, if I'm using sessions for the csrf token (Django 1.11):
CSRF_USE_SESSIONS = True
CSRF_COOKIE_AGE = None
...all forms/post requests on the frontend fail authentication, but I can login fine to the Django admin panel, e.g., csrf token authentication succeeds.
On the other hand, if I'm using cookies for csrf, authentication on the frontend for forms/post requests go through without any problem, but then it fails for the admin login: CSRF verification failed. Request aborted.
Part of my settings.py file looks like this:
SECRET_KEY = os.getenv('DJANGO_SECRET_KEY')
DEBUG = 'DEBUG' in os.environ
# CSRF
# These are commented/uncommented depending on what method I'm testing
# CSRF_USE_SESSIONS = True
# CSRF_COOKIE_AGE = None
# I added the cookie domain setting after I started seeing the problem
# and hoped it would have resolved it; it didn't help.
CSRF_COOKIE_DOMAIN = '.{0}'.format(os.getenv('DOMAIN_NAME', 'mysite.com'))
ALLOWED_HOSTS = [
'.mysite.com',
'.mysite.info',
]
if DEBUG:
ALLOWED_HOSTS.extend(['.mysite.dev'])
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'mainsite',
'constance',
'jstemplate',
'compressor',
]
MIDDLEWARE = [
'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.gzip.GZipMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
'mainsite.middleware.Guid',
'mainsite.middleware.SiteLang',
]
If I set DEBUG to True, I have no issues whatsoever with CSRF token authentication, both on the frontend as with logging into the Django admin panel.
I'm also using Redis as a cache. Am I missing something crucial that is causing this CSRF error? I must point out, there was a point in which I was not getting this error, but I cannot for the life of me pinpoint what change would have created this behavior with the CSRF token.
I also have the same issue.
I solve this by
1. pip install django-sslserver.
2. Put sslserver in the INSTALLED_APPS.
3. python manage.py runsslserver
i'm trying to find bug for few hours now but nothing comes out.
Django gives me this error message when i'm trying to access request.SESSION from view. No other errors.
'WSGIRequest' object has no attribute 'SESSION'
Here is my Django settings what points to sessions and authentication. Most of them are set to their defaults.
AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',)
AUTH_PROFILE_MODULE = 'alkimikis.users.models.UserProfile'
INSTALLED_APPS = ['django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.auth', 'django.contrib.admin', 'alkimikis.users']
MIDDLEWARE_CLASSES = ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware')
SESSION_ENGINE = 'django.contrib.sessions.backends.db'
Ideas for solution or deeper debugging? Anyone?
It's request.session. Lower case.
To debug, use the unit test framework. You can then add print statements and see the results.
print request
Very helpful.