如何使用Delete链接删除对象时包含@ Html.AntiForgeryToken()

时间:2012-04-23 00:23:09

标签: asp.net-mvc-3 antiforgerytoken

我有以下ajax.actionlink调用Delete action method来删除对象: -

 @if (!item.IsAlreadyAssigned(item.LabTestID))
        { 
        string i = "Are You sure You want to delete (" + @item.Description.ToString() + ") ?";
           @Ajax.ActionLink("Delete",
       "Delete", "LabTest",
      new { id = item.LabTestID },

new AjaxOptions
{ Confirm = i,
    HttpMethod = "Post",
    OnSuccess = "deletionconfirmation",
    OnFailure = "deletionerror"
})
} 

但是有没有办法让@Html.AntiForgeryToken()包含Ajax.actionlink删除调用,以确保没有攻击者可以发送错误的删除请求?

BR

2 个答案:

答案 0 :(得分:16)

您需要使用Html.AntiForgeryToken帮助器来设置cookie并发出具有相同值的隐藏字段。发送AJAX请求时,您还需要将此值添加到POST数据中。

所以我会使用普通链接而不是Ajax链接:

@Html.ActionLink(
    "Delete", 
    "Delete", 
    "LabTest", 
    new { 
        id = item.LabTestID
    }, 
    new { 
        @class = "delete",
        data_confirm = "Are You sure You want to delete (" + item.Description.ToString() + ") ?"
    }
)

然后将隐藏字段放在DOM中的某个位置(例如在关闭正文标记之前):

@Html.AntiForgeryToken()

最后不引人注意地AJAX化删除锚:

$(function () {
    $('.delete').click(function () {
        if (!confirm($(this).data('confirm'))) {
            return false;
        }

        var token = $(':input:hidden[name*="RequestVerificationToken"]');
        var data = { };
        data[token.attr('name')] = token.val();
        $.ajax({
            url: this.href,
            type: 'POST',
            data: data,
            success: function (result) {

            },
            error: function () {

            }
        });

        return false;
    });
});

现在,您可以使用Delete属性装饰ValidateAntiForgeryToken操作:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id)
{
    ...
}

答案 1 :(得分:2)

通过Bronx修改答案:

$.ajaxPrefilter(function (options, localOptions, jqXHR) {
    var token, tokenQuery;
    if (options.type.toLowerCase() !== 'get') {
        token = GetAntiForgeryToken();
        if (options.data.indexOf(token.name)===-1) {
            tokenQuery = token.name + '=' + token.value;
            options.data = options.data ? (options.data + '&' + tokenQuery) 
                : tokenQuery;
        }
    }
});

结合Jon White

的答案
function GetAntiForgeryToken() {
  var tokenField = $("input[type='hidden'][name$='RequestVerificationToken']");
  if (tokenField.length == 0) { return null; 
  } else {
  return {
     name: tokenField[0].name,
     value: tokenField[0].value
  };
}

编辑 抱歉 - 意识到我在这里重新发明轮子SO asp-net-mvc-antiforgerytoken-over-ajax/16495855#16495855