Home > database >  How to do an AJAX post with MVC AntiForgeryToken
How to do an AJAX post with MVC AntiForgeryToken

Time:07-19

This delete button will only call the controller method if I remove the ValidateAntiForgeryToken attribute. How can I change either of these methods to keep the antiforgery token. I am assuming .NET does not believe this way of deleting is safe and causes the AJAX to not hit the controller. I would like to find the most secure way possible to send a delete call.

Delete button AJAX.

$("table").on("click", ".btn-delete", function (e) {
            var thisId = $(this).data('id');
            if (confirm("Are you sure you want to delete this item?")) {
                $.post('/AdminPortal/Client/Delete/', { id: thisId }, function (data) {
                    window.location.href = "/AdminPortal/Client/Index";
                });
            }
        });

Delete Method Controller

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Delete(string id)
{
    //add priv check here in the future
    var client = baseSvc.ClientRepo.GetById(long.Parse(id));
    if (client != null)
    {
        client.IsActive = false;
        baseSvc.ClientRepo.Save(client);
    }
    return RedirectToAction(nameof(Index), new { area = nameof(AdminPortal) });
 }

CodePudding user response:

What I have in my code for this is the following:

global JavaScript function

// CSRF (XSRF) security
function addAntiForgeryToken(data) {
    //if the object is undefined, create a new one.
    if (!data) {
        data = {};
    }
    //add token
    var tokenInput = $('input[name=__RequestVerificationToken]');
    if (tokenInput.length) {
        data.__RequestVerificationToken = tokenInput.val();
    }
    return data;
};

in my _Layout.cshtml (somewhere so it is on every page)

@Html.AntiForgeryToken()

usage: Then before doing your POST you can call the method to add a token to your data:

let data = addAntiForgeryToken({ id: thisId });
$.post('/AdminPortal/Client/Delete/', data, function (response) {
    window.location.href = "/AdminPortal/Client/Index";
});
  • Related