raagin/django-streamfield

Not working with CSRF_USE_SESSIONS=True

Closed this issue · 4 comments

django-streamfield seems not to work with the global setting CSRF_USE_SESSIONS=True (see https://docs.djangoproject.com/en/5.0/ref/settings/#std-setting-CSRF_USE_SESSIONS) due to

headers: {"X-CSRFToken": Cookies.get('csrftoken')}

Adding new blocks or saving changes in blocks in the admin UI works - but saving a model instance after deleting blocks fails with:

Forbidden (403)
CSRF verification failed. Request aborted.

Browser debug console shows:

Uncaught (in promise) 
Object { stack: "I@https://www.xxx.xx/static/dde6e8f9/streamfield/streamfield_widget.js:1:261104\n
...
message: "Request failed with status code 403", name: "AxiosError", code: "ERR_BAD_REQUEST", config: {…}, request: XMLHttpRequest, response: {…} }
​code: "ERR_BAD_REQUEST"
​config: Object { timeout: 0, xsrfCookieName: "XSRF-TOKEN", xsrfHeaderName: "X-XSRF-TOKEN", … }
​message: "Request failed with status code 403"
​name: "AxiosError"

It would be probably smart if the app can automatically use the cookie name from the settings if possible. Bear in mind that the name of both the CSRF and the Session cookie can be freely configured via Django settings (see https://docs.djangoproject.com/en/5.0/ref/settings/#session-cookie-name and https://docs.djangoproject.com/en/5.0/ref/settings/#csrf-cookie-name)

Hello! You're right. Let's try to change:
Cookies.get('csrftoken')
to
document.querySelector('[name=csrfmiddlewaretoken]').value
I think this is a universal solution

You may check it in a new release 2.2.0

thank you for fixing - unfortunately I can't test it any more in my project as I moved to an alternative implementation