Alex Rivera | Logout

How to include the @Html.AntiForgeryToken() when deleting an object using a Delete link

Asked 2012-04-23T00:23:08.593
13

i have the following ajax.actionlink which calls a Delete action method for deleting an object:-

 @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"
})
} 

but is there a way to include @Html.AntiForgeryToken() with the Ajax.actionlink deletion call to make sure that no attacker can send a false deletion request?

BR

Edit
Report

1 Answer

2

Modifying the answer by 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;
        }
    }
});

combined with this answer by 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
  };
}

Edit sorry - realised I am re-inventing the wheel here SO asp-net-mvc-antiforgerytoken-over-ajax/16495855#16495855

answered 2013-06-11T05:19:03.893

Your Answer