How to retrieve/provide a CSRF token to/from Django as an API

空扰寡人 提交于 2019-12-05 11:23:04

You can, as a matter of fact, make this work with CSRF protection, using a whitelist of allowed request origins.

To make this work, you're going to have to use Cross-Origin Resource Sharing (CORS). To achieve this, I'd recommend creating a middleware class that sets up your cross-sharing credentials. There's a great gist that outlines how to use some of the build in cross origin HTTP request headers. You can, if you want, insert the CSRF token via middleware in this way, by changing the origin reference values for the request.

The django-cors-headers app does this for you. You can see how they've negotiated the CSRF tokens in their middleware file, if you're interested.

Refer to the Django REST CORS Docs for more on this (they recommend using django-cors-headers).

If you're still having difficulties, try:

  1. setting the crossDomain parameter of your AJAX request to True. Sometimes, jQuery won't process the request if this isn't specified.
  2. if you're still not receiving a token header in the request at all, try appending the ensure_csrf_cookie() decorator around your view method. Occasionally, when there's no {% csrf_token %} template tag on the page (if you're not rendering a form), Django won't include the token in the request at all.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!