But when we use AJAX to post data to the server asynchronously, we do not use forms most of the times. In those cases we explicitely need to attach the anti forgery token to our data which is sent via ajax. We can do this by some simple javascript.
I am going to describe this approach I used in my asp.net application, for PHP, Java, this approach will be little bit different according to what library you use for CSRF protection. Here I use ASP.NET MVC with Razor view.
First, we will create a form in our parent page which includes only the Anti Forgery token.
1 | <form id="AntiCSRFTokenForm"> @Html.AntiForgeryToken() </form> |
Since this AntiForgeryToken is valid for the page, we can refer to this antiforgery token in any ajax request within the page. If you have many post request that requires request verification, you can inlude this line inside your layout page (or the master page).
Then, create a small script that you can access this token inside the form using a simple function call.
AddAntiCSRFToken = function (data) { var token = $('#AntiCSRFTokenForm input[name=__RequestVerificationToken]').val(); data.__RequestVerificationToken = token; return data; };
This function simple takes a dictionary of data, adds anti forgery above created into the data dictionary and return updated data dictionary.
You can add above code snippet inside a .js file and include in any page where you need anti forgery token to be sent in ajax request.Then, you can send this token with a ajax request as follows.
Here is the jquery ajax request before adding anti forgery token.
$.ajax( url : "/Controller/Action", type: "POST", data: { title: "this is title", age: 45 } );
Here is the ajax request with anti forgery token.
$.ajax( url : "/Controller/Action", type: "POST", data: AddAntiCSRFToken( { title: "this is title", age: 45 }) );
Then you can use [ValidateAntiForgeryToken] attribute in your Controller action to validate the request.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.