1
votes

I'm trying to secure my ajax posts using the anti-forgery mechanism.

First I've added the antiforgerytoken helper method call to my view

@Html.AntiForgeryToken()

and then adjusted my jquery post call

var values = $(this).serialize() + "&__RequestVerificationToken=" + $("input[name='__RequestVerificationToken']").val();

$.post(url, values)
    .success(page.submitSuccess)
    .error(page.submitError)
    .complete(page.submitComplete);

and of course I decorated my action method with the ValidateAntiForgeryToken

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ProjectCreateCommand command)
{
    ....
}

but after submiting the form it throws the A required anti-forgery token was not supplied or was invalid error.

I've deleted the token cookie and also I've restarted the browser.

Am I missing something ?

1

1 Answers

1
votes

if you use $(form).serialize(); it will serialize all input tags, so you can do it by the $.post jquery method. Try something like this:

$("#you_form").submit(function (e) {
    e.preventDefault();
    $.ajax({
       type: 'POST',
       url: $(this).attr("action"), // get url from action attribute, your route setted by the Html.BeginForm()
       data: $(this).serialize(), // serialize all input tags from this form
       success: page.submitSuccess; 
    });
});

There is no problem using @Html.AntiForgeryToken(), serialize method will add this together.

Take a look at this link: http://api.jquery.com/jQuery.post/