[Answered ]-CSRF token error for django app when deploying to AWS server

1👍

If you’ve recently upgraded to Django 4.0, you now need to set CSRF_TRUSTED_ORIGINS – that fixed the error in my case. https://docs.djangoproject.com/en/4.0/ref/settings/#csrf-trusted-origins

👤Hambot

1👍

Try the following order in your middleware as fix:

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    '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',
]

The order in MIDDLEWARE matters because a middleware can depend on other middleware. For instance, AuthenticationMiddleware stores the authenticated user in the session; therefore, it must run after SessionMiddleware. See Middleware ordering for some common hints about ordering of Django middleware classes.

Also remember to include these in settings.py:

# Security & HTTPS settings

SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = False

CORS_ALLOW_ALL_ORIGINS = True
CSRF_TRUSTED_ORIGINS = ['http://<your-domain-or-ip>']

You can learn more about Django Middleware here: https://docs.djangoproject.com/en/4.1/topics/http/middleware/#:~:text=The%20order%20in%20MIDDLEWARE%20matters,ordering%20of%20Django%20middleware%20classes.

👤zora

0👍

Try to reorder the middlewares. They are exequted sequentially. So any middleware passes the request to the next and if something has been blocked it will not be available for the next middleware and so on

👤grisuu

-1👍

The way you describe it working when you comment out the csrfmiddleware sounds identical to the problem I was facing. The way I solved it was by adding a csrf_exempt tag to the ACS endpoint. Credit goes to this short conversation from Github where a user had the same problem.

https://github.com/onelogin/python3-saml/issues/146

Leave a comment