How to handle CSRF in a programmed CORS POST request in django?

I am trying to make a POST request through AJAX from abc.com to a URL from xyz.com (which is a Django application). I get the CSRF token by creating a GET request to the xyz.com URL, but the token changes when an OPTIONS request is made to xyz.com in a request prefixed.

Is there a way to get an OPTIONS request response in the requested request?

Note:

I follow the instructions from the following sources:

+7
ajax django cors csrf
source share
2 answers

Django CSRF protection will allow OPTIONS requests, so no problem with the first step:

https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#how-it-works

If I understand correctly, you want the next request (for example, cross-domain POST) to be resolved. For this to work and pass after Django CSRF protection, the request must send the CSRF token (in the POST data or in the header for AJAX) and the corresponding CSRF cookie.

Now, cross-domain restrictions make it impossible for abc.com to set or read cookies for xyz.com, whether from javascript or from a server-side response. Therefore, such an approach is impossible.

Instead, you will need to apply @csrf_exempt to the view. This will allow any site to post. Therefore, you will need to create some other protection for the submission. Of course, you yourself check the security of your defense. Remember that the Referer and Origin headers can be easily faked with something basic like curl.

+3
source share

See django-cors-headers , you can find how this works more suitable to solve your problem:

 https://github.com/ottoyiu/django-cors-headers/ 

Django-rest-framework recommends http://www.django-rest-framework.org/topics/ajax-csrf-cors

+1
source share

All Articles