CSRF token from the 'X-Csrftoken' HTTP header incorrect

97 views Asked by At

I'm making a web application (a SPA, to be specific) with a separate frontend (React) and backend (DRF). It uses session authentication, but the CSRF token isn't correct for some reason, and I'm having a hard time figuring out why, specifically on the logout route of my application.

Here's how I'm getting and sending the token:

    fetch(APIURL + "/api/csrf-token/")
      .then((response) => {
        return response.json();
      })
      .then((json_response) => {
        const XCSRFToken = json_response["X-CSRFToken"];
        const logout_response = fetch(APIURL + "/api/logout/", {
          headers: {
            "Content-Type": "application/json",
            "X-CSRFToken": XCSRFToken,
          },
          credentials: "include",
          method: "POST",
      })
      // then do stuff

But this yields the following error: CSRF Failed: CSRF token from the 'X-Csrftoken' HTTP header incorrect. I'm not sure where I'm going wrong here because I'm not sure how the CSRF token can be wrong. Before I give the rest of the code, there's one other thing that I'm confused about. When I log in, an HTTP only cookie called csrftoken is passed to my browser; should I be doing anything with that?

Here's my views for getting the CSRF token and logging out.

@api_view(["GET"])
def csrf_token(request):
    response = Response(
        {"detail": "CSRF cookie set", "X-CSRFToken": get_token(request)}
    )
    return response

@api_view(["POST"])
def logout_user(request):
    logout(request)

If there's any other code that I can provide, please let me know.

0

There are 0 answers