'Configuring CSRF tokens with apollo client and graphene-django

I am having trouble properly setting up csrf tokens in the authlink header.

const authLink = setContext((_, { headers }) => {
    const token = localStorage.getItem(AUTH_TOKEN)
  return {
    "headers": {
      'X-CSRFToken' : getCookie('csrftoken'),
      "Authorization": token ? `JWT ${token}` : '',
      ...headers,
    },
  };
});

The request being sent looks ok from the browser devtools, as you can see at the bottom the csrf token looks right? I cleared my browser data to make sure it wasn't old, but I'm not sure if that's effective anyways.

accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Authorization
Connection: keep-alive
Content-Length: 505
content-type: application/json
Host: localhost:8000
Origin: http://localhost:3000
Referer: http://localhost:3000/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36 Edg/89.0.774.63
X-CSRFToken: LsV83sz3Rb5RRIlNcRN3AgnniodwsSMpvXwMGquPGRbvoPpISfKv6MBEf86rVzVp

The error I get through the site is CSRF verification failed. Request aborted

my django server shows Forbidden (CSRF cookie not set.)



Solution 1:[1]

Have you tried to install corsheaders? or are you sure you have this function

function getCookie(name) {
            var cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = cookies[i].trim();
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }

Solution 2:[2]

I had same issue because x-csrftoken was not transmitted in the Request Headers

Here is the fix i have done

On my React code

import { ApolloClient, createHttpLink, InMemoryCache } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
import Cookie from "js-cookie";

const httpLink = createHttpLink({
  uri: '/graphql/',
});

const authLink = setContext((_, { headers }) => {
  return {
    headers: {
      ...headers,
      "x-csrftoken": Cookie.get("csrftoken")
    }
  }
});

const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache()
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Hypér
Solution 2