12

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?

sideshowbarker
  • 62,215
  • 21
  • 143
  • 153
ccr
  • 123
  • 1
  • 1
  • 8

2 Answers2

42

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...

solarissmoke
  • 24,362
  • 12
  • 56
  • 60
10

For anyone who follows this, if you have set CORS_ORIGIN_ALLOW_ALL to True, then you don't need to set the CORS_ORIGIN_WHITELIST variable anymore, as you are allowing every host already.

SOLUTION TO MY PROBLEM - it might help somebody

the problem we had was a peculiar one, we have a Client application sending requests using TokenAuthentication to another application, a CRM built using Django Admin and therefore using SessionAuthentication. When we opened the Django Admin application, the SessionMiddleware was creating automatically a session_id cookie for that domain. When opening the Client application and trying to perform a request, we got the following error:

Error: CSRF Failed: Referer checking failed - https://domainofthedjangoadminapp.com does not match any trusted origins.

That was only because the session_id cookie was already set in the browser and therefore, the request was made using SessionAuthentication instead of TokenAuthentication and failing.

Removing the cookie was obviously fixing the problem.

Tysoncete
  • 161
  • 2
  • 5