Using Django REST Framework with sessions-based CSRF

时间:2018-09-22 22:51:54

标签: django django-rest-framework csrf

I am using Django + Django REST Framework in an environment where I cannot use cookie-based CSRF tokens; therefore I must run with CSRF_USE_SESSIONS = True.

The DRF web UI, however, depends on this cookie for all interactions. It appears this is set by reading the csrftoken cookie and settings the X-CSRFToken header on the subsequent request, which is then consumed by django.middleware.csrf.CsrfViewMiddleware.process_view() if the hidden field is not included in the request body. This is set in this code from rest_framework.templates.rest_framework.base.html:

<script>
  window.drf = {
    csrfHeaderName: "{{ csrf_header_name|default:'X-CSRFToken' }}",
    csrfCookieName: "{{ csrf_cookie_name|default:'csrftoken' }}"
  };
</script>

DRF forms that do not use POST do contain the CSRF token in the form body, so not having the cookie means the web interface does not have access to the CSRF token at all, causing all PUT, PATCH, and DELETE requests to fail with a 403 response.

I believe this is a bug in DRF, but it is possible this is intended behavior. Can someone explain how DRF is intended to be used with CSRF_USE_SESSIONS = True?

1 个答案:

答案 0 :(得分:0)

此问题已在https://github.com/encode/django-rest-framework/pull/6207中修复,并作为DRF 3.9.2的一部分发布。更完整的上下文可以在https://github.com/encode/django-rest-framework/issues/6206上阅读。