11

I'm trying to use Vue.js to do some POST methods to my REST Api that I created with Django Rest Framework. Problem is, I'm getting the CSRF Failed: CSRF token missing or incorrect. error when I post. But I can see the csrf cookie, and it's being added to the headers.

Here's my settings:

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
        'rest_framework.permissions.DjangoModelPermissions'
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication'
    )
}

Here's my Vue.js config:

var csrftoken = Cookies.get('csrftoken');
Vue.http.headers.common['HTTP_X_CSRFTOKEN'] = csrftoken;

And here's the relevant part of the headers that were sent:

Cookie:djdt=hide; tabstyle=raw-tab; sessionid=1gl533mrneudxw3l9l2vg0ja1yowwmeo; csrftoken=dN85bhztB1oVRov87BsUrWTM29Ff9sjn
Host:127.0.0.1:8000
HTTP_X_CSRFTOKEN:dN85bhztB1oVRov87BsUrWTM29Ff9sjn
Origin:http://127.0.0.1:8000
Referer:http://127.0.0.1:8000/agencies/6/add-profiles/

As you can see, Cookie.csrf and the HTTP_X_CSRFTOKEN header match

I'm really stumped. Any suggestions?

5
  • 2
    What CSRF_HEADER_NAME setting you use? I know that HTTP_X_CSRFTOKEN should be X-CSRFTOKEN when you send it, because django conventionally formats it within it's guts: docs.djangoproject.com/en/1.9/ref/settings/#csrf-header-name Commented Mar 9, 2016 at 11:23
  • 1
    do you have your apps in the same domain? or are you using CORS? Commented Mar 9, 2016 at 12:40
  • Yerko Palma is right, it could also be an issue with same-origin request policy or CSRF_COOKIE_HTTPONLY setting. Commented Mar 9, 2016 at 14:50
  • 1
    Kid Binary, you were right. It was the `X-CSRFTOKEN' name Commented Mar 9, 2016 at 17:13
  • as a related question, was the vue-resources library required in order to set the header using the line of code: Vue.http.headers.common['X-CSRFTOKEN']? Commented Oct 26, 2018 at 21:22

2 Answers 2

11

So I'm posting this as an answer to close the question.

The issue was because of the wrong CSRF header name that was sent on request. According to documentation:

As with other HTTP headers in request.META, the header name received from the server is normalized by converting all characters to uppercase, replacing any hyphens with underscores, and adding an 'HTTP_' prefix to the name. For example, if your client sends a 'X-XSRF-TOKEN' header, the setting should be 'HTTP_X_XSRF_TOKEN'.

Also I'm leaving here a reference to my question, which accumulates several problems that may lead to CSRF Failed: CSRF token missing or incorrect. error in Django.

Sign up to request clarification or add additional context in comments.

1 Comment

For anyone using NGINX in their stack: If you leave the setting on default NGINX will not pass your header on. You can circumvent that by sending the header with hyphens instead of underscores and omit the HTTP_ part.Django will then restore that to the correct format. Below code should work for a standard Django set-up var csrftoken = Cookies.get('csrftoken'); Vue.http.headers.common['X-CSRFTOKEN'] = csrftoken;
2

Get token from cookie:

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

var csrftoken = readCookie('csrftoken');

Send token in headers POST:

  this.$http.post('http://'+document.location.host+'/api//',{params: {foo: 'bar'}}, {headers: {"X-CSRFToken":csrftoken }}).then(function (response) {
            this.response = response.data;
        },
        function (response) {
            console.log(response);
        });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.