Search code examples
djangoreactjscsrf

Django CSRF failure, using React forms


I'm having a problem with CSRF with Django and React.

I have read through the already high number of questions around this, as well as the django docs naturally. I have tried every possible combination of different things that should address the issue but am still struggling with it.

Firstly I tried to create a register page, but when I POST to register/ I get CSRF cookie not set, 403.

I have gone so far as disabling the CSRF middleware [bad I know, just trying to get somewhere] and I am getting 405s, method not allowed [attempting to post]. I just thought maybe this is something someone has run into before or sounds familiar and could give some guidance?

I have tried: - adding the decorator @csrf_exempt, - adding the CSRF to the header of a request, - attaching the whole cookie, - attaching a hidden form field with the token.

I am using this seed project: https://github.com/Seedstars/django-react-redux-base if anyone wants to have a look, I've done a bit in React, but not a lot on the Django side, so it isn't far off what's there


Solution

  • You should not disable the csrf check in django. Instead in your form/template simply do {% csrf_token %} not {{ csrf_token }} It will print a hidden form element with value assigned to your csrf token already.

    If you are using ajax, you can simply set your ajax headers globally as:

    $.ajaxSetup({
            beforeSend: function (xhr, settings) {
                // this time double brackets
                xhr.setRequestHeader("X-CSRFToken", "{{csrf_token}}"); 
            }
        });
    

    if you are using fetch then:

    fetch('some/url/here', {
                method: 'GET',
                headers: {
                    'X-CSRFToken': window.CSRF_TOKEN // or pass it in your own way
                }
            }).then(function (response) {
                return response.json()
            })
    

    These are pretty much all the ones i can think of.

    Hope this helps.