How can Prevent Cross site request forgery via Ajax post?

I have a Form with AntiforgeryToken() value in Mvc project. while submiting the form, it validated with their corresponding controller Post action ValidateAntiforgeryToken in MvC project.

It goes to confirmation page. In the confirmation having two button which having hidden Form , this will go to same Post action in previous above.I have added Html.Antiforgerytoken() in that two hidden forms. while clicking the button, we don't need to Form Post[page reload], instead of this Using Ajax post.

I have tried using Ajax post (using Antiforgerytoken ) but it does not hit Post action. Shows 404 error.

Can you please suggest how to enable AntiforgryToken using Ajax post? For that what type of code handle and where do it add?

Form details:

 <form  method="post" action="">
     @Html.AntiForgeryToken()
     <input type="hidden" name="Name" value="@downloadInfo.Name" />
     <input type="hidden" name="Company" value="@downloadInfo.Company" />
     <input type="hidden" name="Email" value="@downloadInfo.Email" />
     <input type="hidden" name="Phone" value="@downloadInfo.Phone" />
 </form>  

Ajax Post:

$.ajax({     
    url: url,
    type: 'POST',
    data: JSON.stringify(Formdatas),
    contentType: 'application/json; charset=utf-8',
    beforeSend: showLoadingGraphic(id),
    success: onSuccessfulPost
});

If you've received a 404 it's not from the token, you had an invalid URL or method. You are including your token in your ajax form post, so look by using the tool Fiddler what URL is being requested and fix that first.

I'm guessing your Ajax call using 'URL' is incorrect


Try generating your form as it should (using the Html.BeginForm helper):

@using (Html.BeginForm("SomeAction", "SomeController", FormMethod.Post, new { id = "myForm" }))
{
    @Html.AntiForgeryToken()
    <input type="hidden" name="Name" value="@downloadInfo.Name" />
    <input type="hidden" name="Company" value="@downloadInfo.Company" />
    <input type="hidden" name="Email" value="@downloadInfo.Email" />
    <input type="hidden" name="Phone" value="@downloadInfo.Phone" />
}

and then:

var myForm = $('#myForm');
$.ajax({     
    url: myForm.attr('action'),
    type: myForm.attr('method'),
    data: myForm.serialize(),
    beforeSend: showLoadingGraphic(id),
    success: onSuccessfulPost
});

Now the antiforgery token and the hidden fields will be properly sent to the server.

链接地址: http://www.djcxy.com/p/62770.html

上一篇: 从Cross保护Web API

下一篇: 如何防止跨站点请求通过Ajax post伪造?