CSRF validation does not work on Django using HTTPS

ccr picture ccr · Aug 9, 2016 · Viewed 11.7k times · Source

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?

Answer

solarissmoke picture solarissmoke · Aug 9, 2016

Your CSRF_TRUSTED_ORIGINS setting is wrong - change it to:

CSRF_TRUSTED_ORIGINS = ['front.bluemix.net']

The setting requires a hostname only, not a scheme. A scheme is redundant anyway because the setting only has any effect when connecting over HTTPS.

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