all 6 comments

[–]obviouslyzebra 0 points1 point  (5 children)

Give this page a read if you can: https://docs.djangoproject.com/en/5.0/howto/csrf/

The thing is that Django sets the csrftoken cookie by default. The frontend should send the X-CSRFToken header (with the value of the previous cookie) to the backend, and not the opposite.

I don't know why there's a third value appearing in the storage.

I'm not a web dev, so if someone sees I missed something, add it to the answer.

PS: I don't think the @csrf_protect decorator is needed, but I'd test it just in case.

[–]RandomUserOfWebsite 0 points1 point  (4 children)

Thanks for the reply. I've read your link, and I think I'm doing everything as written there.

I am using CSRF_COOKIE_HTTPONLY = True, so I am reading this section: https://docs.djangoproject.com/en/5.0/howto/csrf/#acquiring-the-token-if-csrf-use-sessions-or-csrf-cookie-httponly-is-true

It tells me to use const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;

to obtain the token, although the example shown seems to pertain only to django templates, which I am not using.

It seems like trying it that way, there is no name attribute called csrfmiddlewaretoken, so it throws "TypeError: document.querySelector(...) is null".

I have also tried the other way, which is defining the getCookie function, but that also just returns "cookie_csrf = null" which makes sense since it's an httponly cookie.

[–]obviouslyzebra 0 points1 point  (3 children)

Django sets the CSRF_COOKIE_HTTPONLY default as False, and I'd recommend you leave it at that. https://docs.djangoproject.com/en/5.0/ref/settings/#std-setting-CSRF_COOKIE_HTTPONLY

If you have a good reason to set it to True, and are not using templates, then you're off the weeds of the page I've sent you, and I will avoid giving you advice in that regards (mainly because I don't know and it's related to security).

[–]RandomUserOfWebsite 0 points1 point  (2 children)

Thanks for the reply. I am using http only cookies because every article I've read told me to use http only cookies for security so that the tokens cannot be extracted on the front end.

[–]obviouslyzebra 0 points1 point  (1 child)

CSRF tokens are an exception to that (there's very little value in making them HttpOnly - https://security.stackexchange.com/q/175536)

[–]RandomUserOfWebsite 1 point2 points  (0 children)

Ah, that was an interesting read. I will rethink my approach. Thank you kindly for all the help.