CSRF verification failing in django/backbone.js

前提是你 提交于 2020-01-16 02:52:07

问题


I'm trying to recreate a small project from lightweight django - https://github.com/lightweightdjango/examples/tree/chapter-5

I'm getting a CSRF error when trying to login with the superuser account. Below is my models.js

(function ($, Backbone, _, app) {

    // CSRF helper functions taken directly from Django docs
    function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/i.test(method));
    }

    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 = $.trim(cookies[i]);
                // 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;
    }

    // Setup jQuery ajax calls to handle CSRF
    $.ajaxPrefilter(function (settings, originalOptions, xhr) {
        var csrftoken;
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            // Send the token to same-origin, relative URLs only.
            // Send the token only if the method warrants CSRF protection
            // Using the CSRFToken value acquired earlier
            csrftoken = getCookie('csrftoken');
            xhr.setRequestHeader('X-CSRFToken', csrftoken);
        }
    });

I tried cloning the entire project to my localfolder. I'm still getting the CSRF error.

Django merely provides the API for the project - templating etc is handled by Backbone.js

Please let me know if i need to post more code.

my login template if it's of any help

  var LoginView = FormView.extend({
        id: 'login',
        templateName: '#login-template',
        submit: function (event) {
            var data = {};
            FormView.prototype.submit.apply(this, arguments);
            data = this.serializeForm(this.form);
            $.post(app.apiLogin, data)
                .done($.proxy(this.loginSuccess, this))
                .fail($.proxy(this.failure, this));
        },
        loginSuccess: function (data) {
            app.session.save(data.token);
            this.done();
        }
    });

回答1:


It's not clear from the code sample if you are defining the CRSF token. If you are using django templates, you can set {% csrf_token %} to be your CRSF token, somewhere in your code.




回答2:


I had exactly the same issue. Then as suggested in page 111 of the book:

This assumes that the project is using the default cookie name csrftoken. If needed, this token could be configured via the configuration parsed by app.js.

I added "csrftoken": "{% csrf_token %}" to the "config" section in index.html:

...
<script src="{% static 'board/vendor/backbone.js' %}"></script>
<script id="config" type="text/json">
    {
        "models": {},
        "collections": {},
        "views": {},
        "router": null,
        "csrftoken": "{% csrf_token %}", //added this
        "apiRoot": "{% url 'api-root' %}",
        "apiLogin": "{% url 'api-token' %}"
    }
</script>
<script src="{% static 'board/js/app.js' %}"></script>
...

With this change, the error was fixed and I was able to log in.



来源:https://stackoverflow.com/questions/32552013/csrf-verification-failing-in-django-backbone-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!