I am debugging my Django project deployed in the cloud. It does not have a domain name yet. I cannot login though the /admin/
page because of the CSRF error:
CSRF verification failed. Request aborted.
I am also trying to debug it using my frontend deployed in machine at localhost:3000
. The same case, I get a 403
response signifying the CSRF verification failure. I want to bypass this on DEBUG=True
for the purpose of debugging my APIs.
I found this thread, and followed one of its answers: https://stackoverflow.com/a/70732475/9879869. I created a Middleware supposedly disabling the CSRF when DEBUG=True
.
#utils.py
from project import settings
from django.utils.deprecation import MiddlewareMixin
class DisableCSRFOnDebug(MiddlewareMixin):
def process_request(self, request):
attr = '_dont_enforce_csrf_checks'
if settings.DEBUG:
setattr(request, attr, True)
I added it to my MIDDLEWARE
. It is the last entry in the list.
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"corsheaders.middleware.CorsMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"project.utils.DisableCSRFOnDebug"
]
After all of this, I still cannot login to my Django admin and my locally deployed frontend still gets the CSRF verification failure. I do not want the csrf_exempt
option since it does not make sense placing it on an important endpoint/view -- the Login.
Here are my additional configuration on settings.py
.
X_FRAME_OPTIONS = 'SAMEORIGIN'
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = [
'http://localhost',
'http://localhost:3000',
'https://example.com',
]
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
CSRF_TRUSTED_ORIGINS = [
'http://localhost',
'http://localhost:3000',
'https://example.com',
]
What is wrong with my configuration? How can I disable CSRF in Debug mode?