0

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?

Nikko
  • 1,410
  • 1
  • 22
  • 49

1 Answers1

0

first of all deactivating CSRF and security middlewares even in local development is not good idea it can cost you a lot during deployment better to find out why it's broken,and for your Middleware that doesn't work its because the Middleware ordering is matter!

Read the docs

And i think the problem is in CSRF_COOKIE_SECURE =True Due

CSRF_COOKIE_SECURE¶ Default: False

Whether to use a secure cookie for the CSRF cookie. If this is set to True, the cookie will be marked as “secure”, which means browsers may ensure that the cookie is only sent with an HTTPS connection.

Do you use https in local development?

This is good for read and more info too. Docs of Django CSRF token