1
votes

I have a Django app with about a dozen views that I am currently hosting on Heroku. I can do POST requests just fine to the app when directly going to the app url, and I have the 'django.middleware.csrf.CsrfViewMiddleware' enabled. I am running Django 2.1

I am currently having an issue where I am trying to embed this Django app within an iframe, on another site that I host on Weebly. I always get a 403 error when trying to do a post on any of the Django forms. The reason is "CSRF cookie not set."

I am doing this through Chrome on Ubuntu. I checked the Applications tab in the Developer console, and do see the csrftoken key-value pair set in the cookie for the Heroku domain. The Weebly domain does not contain the csrftoken key-value pair. I figured it would just use the cookie from the Heroku app domain and use the csrftoken, but that doesn't appear to be the case.

In Django, here are my settings regarding CSRF:

CSRF_COOKIE_SECURE = False
CSRF_TRUSTED_ORIGINS = ['example123.herokuapp.com', 
'app123.weebly.com']

I REALLY don't want to disable security or use the csrf_exempt decorator, as that feels like a hack. I am pulling my hair out on this one!

EDIT:

{% csrf_token %} is in the form, and I can see the hidden field "csrfmiddlewaretoken":

<input type="hidden" name="csrfmiddlewaretoken" value="XXXXXXXXXXXXXXXXXXXXXXywkFTfTC9ttYiOTD0O8uF49SvRjaUWgWeLU0h2PjP2">
1
It looks like you need to set CORS headers to allow cookies to be set on a different hostname.Selcuk
Have you tried adding CORS_ORIGIN_ALLOW_ALL = True to your settings.py like @Selcuk has mentioned?waqasgard
do you have {% csrf_token %} in the form & does it contain any value?yedpodtrzitko
I will definitely try your suggestion of adding the CORS headers. So CORS_ORIGIN_ALLOW_ALL = True is all that is needed? The package is called "django-cors-headers", correct?JackR
Ok, so I installed "django-cors-headers". I added the Middleware, and added "corsheaders" to the list of installed apps. I set the following cors parms: CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = False I still get the same error. Is there anything else I'm missing?JackR

1 Answers

0
votes

There are two different things with csrf in django 1. Csrfmiddlewaretoken : {% csrf_token %} example of set-token header 2. CSRFcookie : I don't think that you did this one. example of same request giving different csrf-token

here the images shown are both the examples of one of my app for a specific request

We do often confuse second with the first one. In the second case, the server sets a cookie in the first get request with a csrf token (this is a cookie and not the csrfmiddlewaretoken ), it needs to be sent every-time for csrf cookie verification. This is done by the browser itself and we mostly don't notice it. However the problem arises with using CORS (different origins of request like android/angular app etc).