PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, September 8, 2022

[FIXED] How to do an AJAX post with MVC AntiForgeryToken

 September 08, 2022     ajax, asp.net-core, post, websecurity     No comments   

Issue

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) });
 }

Solution

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


Answered By - lordvlad30
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing