0

I have sessions enabled in Django to use Django's authentication framework.

From a html page served by Django, and after authenticating as a user with sufficient permissions, I'm trying to send a PATCH request via JQuery's ajax() function, and I'm getting HTTP 403 errors with the response detail CSRF Failed: CSRF token missing or incorrect.

What I've done so far:

I'm including the correct csrf token in the X-CSRF-TOKEN header field. I've set SESSION_COOKIE_HTTPONLY = False.

The cookie sent in the ajax request includes the sessionid. If I get rid of this sessionid, the request succeeds.To do so, I either delete the session cookies in the browser or edit the PATCH request in the browser's developer tools and resend it with the sessionid deleted from the Cookie header field. Obviously I need to re-login as soon as I refresh the page, but in the meantime, I can PATCH to my heart's content.

So far I couldn't find out why the presence of the sessionid cookie makes Django deny the request.

Endre Both
  • 5,540
  • 1
  • 26
  • 31
  • 1
    What view are you sending the requests to? If it's a `PATCH` request it's maybe a Django-Rest-Framework powered API? – Bernhard Vallant Jan 28 '19 at 20:15
  • 1
    According to the django docs the header name is `X-CSRFToken`. Have you changed the `CSRF_HEADER_NAME` setting to reflect the different header name? – Fynn Becker Jan 28 '19 at 20:28
  • 1
    Refer to this answer https://stackoverflow.com/a/30875830/6280433 – Arpit Svt Jan 28 '19 at 21:37
  • After correcting the header name (thanks Fynn!), the token is accepted. – Endre Both Jan 29 '19 at 08:14
  • Thanks Arpit for the pointer to the other question which helped me understand why it worked without the session id. After setting up the REST framework to use DjangoModelPermissions, the API access restrictions are shaping up fine. It's only curl requests that have stopped working now, even when providing user credentials and/or a token, but that's a minor point. – Endre Both Jan 29 '19 at 08:18
  • Apparently, for curl to work you have to add BasicAuthentication (in the REST_FRAMEWORK settings, or, if using specific authentication types for views, in the view). – Endre Both Jan 29 '19 at 08:39

0 Answers0