Express.js csrf token with jQuery Ajax

可紊 提交于 2019-11-29 15:42:13

Send the CSRF token inside the payload message:

$('button').click(function (e) {
    e.preventDefault();
    var text = $('.favori').val();
    alert(text);
    $.post(
        "/form",
        {
            text: text,
            _csrf : $('meta[name="_csrf"]').attr('content')
        }, function (data) {
            console.log(data);
        });
});

To facilitate your work I think you can create a Jquery plugin to do it, something like this:

(function( $ ) {
    $.postCSRF = function(to, message, callback) {
        message._csrf = $('meta[name="_csrf"]').attr('content');
        $.post(to, message, callback);
    };
}( jQuery ));

// Usage example:
$.postCSRF('/form',{text:'hi'},function(res) {
    console.log(res);
});

Example: http://jsfiddle.net/w7h4Lkxn/

Check the header to see if its passing the tampered token in the cookie or as part of the form data. It looks like your setup is for using cookies. So changing it on the form shouldn't affect the cookie. Lemme know if that helps reveal the issue.

your doing everything exactly right but you have to disable checking for the cookie entirely!

var csrfProtection = csurf({ cookie: false });

the author mentions it here https://github.com/expressjs/csurf/issues/52

thanks for the above code with the header post as this was crucial for validating the express session token and i have shared it with others

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