Search code examples
pythondjangodjango-rest-frameworkibm-clouddjango-csrf

CSRF validation does not work on Django using HTTPS


I am developing an application which the frontend is an AngularJS API that makes requests to the backend API developed in Django Rest Framework.

The frontend is on the domain: https://front.bluemix.net
And my backend is on the domain: https://back.bluemix.net

I am having problems making requests from the frontend API to the backend API. The error is this:

Error: CSRF Failed: Referer checking failed - https://front.bluemix.net does not match any trusted origins.

I am using CORS and I have already included the following lines in my settings.py in the Django backend API:

ALLOWED_HOSTS = []

CORS_ALLOW_CREDENTIALS = True

CORS_ORIGIN_ALLOW_ALL = True

CORS_ALLOW_CREDENTIALS = True


CSRF_TRUSTED_ORIGINS = ['https://front.bluemix.net/']

CORS_REPLACE_HTTPS_REFERER = True

CSRF_COOKIE_DOMAIN = 'bluemix.net'

CORS_ORIGIN_WHITELIST = (
    'https://front.bluemix.net/',
    'front.bluemix.net',
    'bluemix.net',
)

Anyone knows how to solve this problem?


Solution

  • Django 4.0 and above

    For Django 4.0 and above, CSRF_TRUSTED_ORIGINS must include scheme and host, e.g.:

    CSRF_TRUSTED_ORIGINS = ['https://front.bluemix.net']
    

    Django 3.2 and lower

    For Django 3.2 and lower, CSRF_TRUSTED_ORIGINS must contain only the hostname, without a scheme:

    CSRF_TRUSTED_ORIGINS = ['front.bluemix.net']
    

    You probably also need to put something in ALLOWED_HOSTS...