How to handle CSRF in preflighted CORS POST request in django?

I am trying to make POST request via AJAX from abc.com to URL from xyz.com (which is a Django application). I am getting CSRF token by making a GET request to a URL on xyz.com , but the token changes when an OPTIONS request is made to xyz.com in the preflighted request.

Is there any way to get the response of OPTIONS request in the preflighted request ?

Note:

I am following instructions from following sources :

  • https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
  • https://developer.mozilla.org/en/docs/HTTP/Access_control_CORS
  • http://www.html5rocks.com/en/tutorials/cors/

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

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

    If I understand correctly, you then want the next request (eg a cross-domain POST) to be allowed through. For this to work and get past Django's CSRF protection, the request must send a CSRF token (in POST data or in header for AJAX) and a matching CSRF cookie.

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

    Instead you will have to apply @csrf_exempt to the view. This would allow any site to post to it. Therefore, you'll need to build in some other protection to the view. You are, of course, on your own in checking the security of your protection. Remember that 'Referer' and 'Origin' headers can easily be forged with something as basic as curl.


    See django-cors-headers , you may find it how it 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

    链接地址: http://www.djcxy.com/p/75568.html

    上一篇: 在C中实现一个shell

    下一篇: 如何在django中预处理CORS POST请求中处理CSRF?