ASP.net MVC AntiForgeryToken over AJAX

前端 未结 6 1887
清酒与你
清酒与你 2020-12-10 16:08

I am currently developing an MVC application in ASP.net. I am using AJAX.ActionLink to provide a delete link in a list of records, however this is very insecure. I have put

6条回答
  •  無奈伤痛
    2020-12-10 16:13

    To piggyback on the $.ajaxPrefilter answers, I added the token to both options and originalOptions rather than the jqXHR headers. This does require the token to be somewhere in a form on your page.

    $.ajaxPrefilter(function (options, originalOptions, jqXHR) {
        var token = $('input[name="__RequestVerificationToken"]');
        if (token.length > 0) {
            var data = options.data;
            var dataArray = originalOptions.data;
            if (data && !data.includes('__RequestVerificationToken')) {
                options.data = data + '&__RequestVerificationToken=' + token.val();
            }
            if (dataArray && !('__RequestVerificationToken' in dataArray)) {
                var tokenObject = { name: '__RequestVerificationToken', value: token.val() };
                originalOptions.data.push(tokenObject);
            }
        }
    });
    

    Keep in mind that this will add this token to every single AJAX request on your page, so you may want to filter by the options.url string or options.type == 'POST'.

提交回复
热议问题