seawolf
seawolf

Reputation: 2195

Using Django REST Framework with sessions-based 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?

Upvotes: 6

Views: 1074

Answers (1)

seawolf
seawolf

Reputation: 2195

This was fixed in https://github.com/encode/django-rest-framework/pull/6207 and released as part of DRF 3.9.2. More complete context can be read at https://github.com/encode/django-rest-framework/issues/6206.

Upvotes: 1

Related Questions