#Forbidden (CSRF cookie not set.)

2 messages · Page 1 of 1 (latest)

oblique zealot
#

Code:

js:

 let csrftoken = getCookie("csrftoken");
    console.log("cookie", csrftoken)
    let requestBody = {
        message: userMessage,
    };

    const requestOptions = {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "X-CSRFToken": csrftoken,
            "Access-Control-Allow-Credentials": true,
        },
        body: JSON.stringify(requestBody),
        credentials: 'same-origin'
    };


    try {
        console.log(requestBody)
        const res = await fetch(API_URL, requestOptions);

view:

def get_response(request: HttpRequest) -> HttpRequest:
    if request.method == "POST":
        data = json.loads(request.body)
        print("headers:",request.headers)
        message = data['message']
        response_data = generate_response(message=message)
        response_data['Access-Control-Allow-Origin'] = 'http://127.0.0.1:8000'
        response_data['Access-Control-Allow-Credentials'] = 'true'
        return JsonResponse(response_data)
    else:
        return JsonResponse({"error": "Method Not Allowed"}, status=405)

will result in:
Forbidden (CSRF cookie not set.)

headers printed in the view:

headers: {'Content-Length': '16', 'Content-Type': 'application/json', 'Host': 'localhost:8000', 'Connection': 'keep-alive', 'Sec-Ch-Ua': '"Google Chrome";v="123", "Not:A-Brand";v="8", "Chromium";v="123"', 'Access-Control-Allow-Credentials': 'true', 'Sec-Ch-Ua-Mobile': '?0', 'X-Csrftoken': 'xBZyCfgmBfPNvJpeU5B285UMcynSzG5U', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36', 'Sec-Ch-Ua-Platform': '"Windows"', 'Accept': '/*', 'Origin': 'http://127.0.0.1:8000/', 'Sec-Fetch-Site': 'cross-site', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Dest':
'empty', 'Accept-Encoding': 'gzip, deflate, br, zstd', 'Accept-Language': 'en-US,en;q=0.9'}

('X-Csrftoken' is inside headers and there is a cookie called csrftoken in browser

#

The fix was to instead of having a different url for it i just do it at home if it is a post request, idk why that worked