我已经在我的应用程序中实现了对CSRF攻击的缓解,这是我在互联网上的一些博客文章上读到的信息。特别是这些帖子一直是我实现的驱动力

ASP的最佳实践。NET MVC从ASP。NET和Web工具开发人员内容团队 跨站点请求伪造攻击的剖析,来自Phil Haack的博客 ASP中的AntiForgeryToken。NET MVC框架- Html。来自David Hayden博客的AntiForgeryToken和ValidateAntiForgeryToken属性

基本上,这些文章和建议说,为了防止CSRF攻击,任何人都应该实现以下代码:

在接受POST Http谓词的每个操作上添加[ValidateAntiForgeryToken] (HttpPost) (ValidateAntiForgeryToken) SomeAction(SomeModel模型){ } 在向服务器提交数据的表单中添加<%= Html.AntiForgeryToken() %> helper

无论如何,在我的应用程序的某些部分,我做Ajax post与jQuery到服务器没有任何形式。例如,当我让用户点击图像来执行特定操作时就会发生这种情况。

假设我有一个包含活动列表的表。我在表的一列上有一个图像,说“标记活动已完成”,当用户单击该活动时,我正在做Ajax POST如下示例:

$("a.markAsDone").click(function (event) {
    event.preventDefault();
    $.ajax({
        type: "post",
        dataType: "html",
        url: $(this).attr("rel"),
        data: {},
        success: function (response) {
            // ....
        }
    });
});

在这些情况下,我如何使用<%= Html.AntiForgeryToken() %> ?我是否应该在Ajax调用的数据参数中包含helper调用?

很抱歉写了这么长时间,非常感谢你的帮助

编辑:

根据jayrdub的回答,我用下面的方式

$("a.markAsDone").click(function (event) {
    event.preventDefault();
    $.ajax({
        type: "post",
        dataType: "html",
        url: $(this).attr("rel"),
        data: {
            AddAntiForgeryToken({}),
            id: parseInt($(this).attr("title"))
        },
        success: function (response) {
            // ....
        }
    });
});

当前回答

我喜欢360Airwalk提供的解决方案,但它可能会有所改进。

第一个问题是,如果使用空数据创建$.post(), jQuery不会添加Content-Type标头。NET MVC无法接收和检查令牌。所以你必须确保页眉一直在那里。

另一个改进是支持所有带有内容的HTTP动词:POST、PUT、DELETE等。虽然可以在应用程序中只使用post,但最好有一个通用的解决方案,并验证使用任何谓词接收的所有数据都具有防伪造令牌。

$(document).ready(function () {
    var securityToken = $('[name=__RequestVerificationToken]').val();
    $(document).ajaxSend(function (event, request, opt) {
        if (opt.hasContent && securityToken) {   // handle all verbs with content
            var tokenParam = "__RequestVerificationToken=" + encodeURIComponent(securityToken);
            opt.data = opt.data ? [opt.data, tokenParam].join("&") : tokenParam;
            // ensure Content-Type header is present!
            if (opt.contentType !== false || event.contentType) {
                request.setRequestHeader( "Content-Type", opt.contentType);
            }
        }
    });
});

其他回答

我认为你所要做的就是确保“__RequestVerificationToken”输入包含在POST请求中。另一半信息(即用户cookie中的令牌)已经通过AJAX POST请求自动发送。

例如,

$("a.markAsDone").click(function (event) {
    event.preventDefault();
    $.ajax({
        type: "post",
        dataType: "html",
        url: $(this).attr("rel"),
        data: { 
            "__RequestVerificationToken":
            $("input[name=__RequestVerificationToken]").val() 
        },
        success: function (response) {
            // ....
        }
    });
});

我发现的解决方案不是针对ASPX,而是针对剃刀,但相当可行的问题。

我通过在请求中添加AntiForgery解决了这个问题。HTML Helper不会用调用创建HTML id

@Html.AntiForgeryToken()

为了将令牌添加到postrequest,我只是用jquery添加了AntiForgery id到隐藏字段:

$("input[name*='__RequestVerificationToken']").attr('id', '__AjaxAntiForgeryForm');

这导致控制器接受带有[ValidateAntiForgeryToken]属性的请求

发现这个非常聪明的想法从https://gist.github.com/scottrippey/3428114为每$。Ajax调用它,修改请求并添加令牌。

// Setup CSRF safety for AJAX:
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
    if (options.type.toUpperCase() === "POST") {
        // We need to add the verificationToken to all POSTs
        var token = $("input[name^=__RequestVerificationToken]").first();
        if (!token.length) return;

        var tokenName = token.attr("name");

        // If the data is JSON, then we need to put the token in the QueryString:
        if (options.contentType.indexOf('application/json') === 0) {
            // Add the token to the URL, because we can't add it to the JSON data:
            options.url += ((options.url.indexOf("?") === -1) ? "?" : "&") + token.serialize();
        } else if (typeof options.data === 'string' && options.data.indexOf(tokenName) === -1) {
            // Append to the data string:
            options.data += (options.data ? "&" : "") + token.serialize();
        }
    }
});

我使用了一个简单的js函数

AddAntiForgeryToken = function(data) {
    data.__RequestVerificationToken = $('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').val();
    return data;
};

由于页面上的每个表单都有相同的令牌值,所以只需在最顶部的母版页中添加如下内容即可

<%-- used for ajax in AddAntiForgeryToken() --%>
<form id="__AjaxAntiForgeryForm" action="#" method="post"><%= Html.AntiForgeryToken()%></form>  

然后在ajax调用do(编辑以匹配第二个示例)

$.ajax({
    type: "post",
    dataType: "html",
    url: $(this).attr("rel"),
    data: AddAntiForgeryToken({ id: parseInt($(this).attr("title")) }),
    success: function (response) {
        // ....
    }
});

对360Airwalk解决方案略有改进。这将在javascript函数中嵌入防伪造令牌,因此@Html.AntiForgeryToken()不再需要包含在每个视图中。

$(document).ready(function () {
    var securityToken = $('@Html.AntiForgeryToken()').attr('value');
    $('body').bind('ajaxSend', function (elm, xhr, s) {
        if (s.type == 'POST' && typeof securityToken != 'undefined') {
            if (s.data.length > 0) {
                s.data += "&__RequestVerificationToken=" + encodeURIComponent(securityToken);
            }
            else {
                s.data = "__RequestVerificationToken=" + encodeURIComponent(securityToken);
            }
        }
    });
});