Thursday, May 23, 2013

ValidateAntiForgeryToken with postback and json in MVC

ValidateAntiForgeryToken as explained here from Stack Overflow
"MVC's Anti-Forgery Token support writes a unique value to an HTTP-only cookie and then the same value is written to the form. When the page is submitted, an error is raised if the cookie value doesn't match the form value.
It's important to note that the feature prevents cross site request forgeries. That is, a form from another site that posts to your site in an attempt to submit hidden content using an authenticated user's credentials. The attack involves tricking the logged in user into submitting a form.
The feature doesn't prevent any other type of data forgery or tampering based attacks." 
To use this feature in MVC, you need to add the [HttpPostAuthorizeValidateAntiForgeryToken] attribute to your HttpPost methods.
Example:

[HttpPostAuthorizeValidateAntiForgeryToken]
public ActionResult MyPostBackMethod(string MyTextInputstring MyDropDown){
   //Do some stuff
}

In your view, you also need to add the following, if we are speaking Razor 
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @*Some HTML*@
}

Now, if we have some client side scripts, this will not work as the HttpPost method is expecting to use the ValidateAntiForgeryToken attribute.

What we need to do is simply add the following value to our json response

__RequestVerificationToken: $('[name=__RequestVerificationToken]').val()

Example:
<script type="text/javascript">
        var data = {
            MyTextInput: $('#txbMyTextInput' + id).val(),
            MyDropDown: $('#cbMyDropDown' + id).is(':checked'),
            __RequestVerificationToken: $('[name=__RequestVerificationToken]').val()
        };
 
        $.post('MyPostBackMethod', data,
        function (result) {
           //do something with result
        }, 'json');
<script />
There is no need to add any parameters on our method on the server side.


No comments:

Post a Comment