Search code examples
reactjsreact-nativecsrfreact-relay

How to handle CSRF tokens with React Relay


I am busy working on a React Native app which talks to a GraphQL api off a Django server.

In React Native I am using React Relay to try and process my GraphQL requests (following the guide found here) but I am having 403 issues with my requests.

The response says CSRF token missing or incorrect and Im trying to figure out the best way to get this working.

I understand that I need to get a CSRF cookie token first then somehow pass that along with my GraphQL Post request but not having much luck. My current implementation of this is as follows...

fetch('http://' + ip + ':8000/sign-in/') 
    .then((response) => {
        const cookieHeader = response.headers.map["set-cookie"]; // This gets me a cookie response with a CSRF token
        fetch('http://' + ip + ':8000/graphql', {
          method: 'POST',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Cookie': cookieHeader, // Try and pass the received cookie to my POST
            'XSRF-TOKEN': cookieHeader // Trying this as well
          },
          body: JSON.stringify({
            query: operation.text,
            variables,
          }),
        }).then(response => {
          console.log('RESPONSE', response) // Currently getting a 403
          return response.json()
        })
    })

But this still gets me a 403 error.

I can't seem to find much more information on how to approach this. Can anybody tell where I'm going wrong, or some suggestions on how to otherwise approach this?

(below is a snapshot of my API requests)

enter image description here


Solution

  • So managed to get it working with the following...

    return getCsrfToken().then(csrfToken => {
        if (csrfToken == null) {
            console.log('CSRF NOT SET')
        }
    
        const url = 'http://' + ip + '/graphql'
        return fetch(url, {
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                    'X-CSRFToken': csrfToken
                },
                body: JSON.stringify({
                    query: operation.text,
                    variables,
                }),
            })
            .then(response => {
                return response.json()
            })
            .catch(error => {
                console.log('POST ERROR', error)
            })
    });
    
    function getCsrfToken() {
        var url = 'http://' + ip + '/graphql';
        return CookieManager.get(url).then(response => {
            return response.csrftoken;
        });
    }