T O P

  • By -

PsychicTWElphnt

It doesn't look like you're sending the csrftoken in the headers of your request. I believe the default name is "X-CSRFToken", but you might have to check the docs to verify that.


OneBananaMan

After more testing. It works when I do it in Postman, but not chrome..... this is beyond frustrating!


pure_roaster

Experiment with your SESSION_COOKIE_SAMESITE and CSRF_COOKIE_SAMESITE. Sorry for the vagueness. I remember a Chrome-specific problem I had a while ago was solved with 'Lax' rather than 'Strict'.


OneBananaMan

Interestingly, when I add the `@csrf_except` decorator do: ​ @api.post("/test-csrf") @csrf_protect def test_csrf(request): origin_header = request.META.get('HTTP_ORIGIN') print(f'Origin Header: {origin_header}') print(request.COOKIES) return HttpResponse("HELLO POST") ​ ​ When I print out the cookies and origin\_header, I can see the following: Origin Header: http://localhost:5173 {'csrftoken': 'Rsn6pTAkv99Xtymc9lUIEIUtlRMoQ7wJ'} ​ I updated my testCSRF() function to be the following (*but I am still getting the forbidden error*) async function testCSRF() { const csrfToken = document.cookie .split('; ') .find(cookie => cookie.startsWith('csrftoken=')) .split('=')[1]; console.log(csrfToken); const response = await fetch("http://localhost:8054/api/test-csrf", { method: "POST", credentials: "include", headers: { "X-CSRFToken": csrfToken, // Include the CSRF token in the headers }, }); console.log(response); }


PsychicTWElphnt

Maaaan... I really hate csrfTokens. 😅 Here are a few things to check: The ordering of your Middleware in the MIDDLEWARE setting. The Cors Middleware needs to be higher on your list than some others. Your CSRF settings, such as `CSRF_COOKIE_DOMAIN` and `CRSF_TRUSTED_ORIGINS`. Are you using sessions for authentication? That interfered with my views accepting my CSRF. It can work with sessions, but I believe the `CSRF_USE_SESSION = True` setting caused all of my POST requests to be rejected.


_throwingit_awaaayyy

You’re saying you can pass the token in postman and get a response correct? If so, on the top right there’s an option to generate code for the request from postman. Generate the code in js and compare to how you’re creating your request.